React中组件的键

时间:2019-04-30 14:30:36

标签: reactjs

我有2个按钮和有关div的信息。当我单击其中一个按钮时,我希望该组件出现在信息块中。但是我的密钥是通过索引转移的。我如何才能使键不成为组件的索引?

import React, { Component } from 'react';
import Donald from '/.Donald';
import John from '/.John';

class Names extends Component {
    state = {
      key: 1
    };

    components =  {
        1: <Donald/>,
        2:<John/>
    };


   showComponent = key => {
     this.setState({ key });
   };

  render() {
    return(
      <div>
        <div className="info">{this.components[this.state.key]}</div>
        <div>
          <button onClick={ () => this.showComponent(1) }>My name Donald</button>
          <button onClick={ () => this.showComponent(2)}>My name John</button>
        </div>
      </div>
    )
  }
}

export default Names;

2 个答案:

答案 0 :(得分:0)

只需编辑一些代码,例如

import React, { Component } from 'react';
import Donald from '/.Donald';
import John from '/.John';

class Names extends Component {
    state = {
      component: null
    };

    components =  {
        'donald': <Donald/>,
        'john' :<John/>
    };

   showComponent = component => {
     this.setState({ component });
   };

  render() {
    return(
      <div>
        <div className="info">{this.components[this.state.component]}</div>
        <div>
          {this.state.component !== 'donald' && <button onClick={ () => this.showComponent('donald') }>My name Donald</button>}
          {this.state.component !== 'john' && <button onClick={ () => this.showComponent('john')}>My name John</button>}
        </div>
      </div>
    )
  }
}

export default Names;

例如,您可以使用switch做一个更好的人,但是您明白了。

答案 1 :(得分:0)

您不需要使用密钥,通过使用different ids and switch-case for components,您可以实现此方案。这是解决问题的有效方法。

const Donald = () => <div>Rendering Component Donald</div>;
const John = () => <div>Rendering Component John</div>;

class Names extends React.Component {
  state = {
    componentId: ""
  };
  components = () => {
    switch (this.state.componentId) {
      case "donald":
        return <Donald />;
      case "john":
        return <John />;
      default:
        return null;
    }
  };
  showComponent = id => {
    this.setState({ componentId: id });
  };

  render() {
    return (
      <div>
        <div className="info">{this.components()}</div>
        <div>
          <button onClick={() => this.showComponent("donald")}>
            My name Donald
          </button>
          <button onClick={() => this.showComponent("john")}>
            My name John
          </button>
        </div>
      </div>
    );
  }
}


ReactDOM.render(<Names />, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id='root' />