1

我想要 3 个按钮和 3 个相关组件。这样当按钮单击时显示其相关组件。这是我的代码:

主要成分:

      class Main extends Component {   constructor(props) {
        super(props);
        this.state = {
          show: false,
        }}  

      onClick(e) {
        e.preventDefault()
        console.log(e.target.id)
        this.setState({ show: !this.state.show });   }  

     renderTabs() {
        var child = this.props.child;
        var items = [];
        __.forEach(child, (item, index) => {
          items.push(
            <div>
              <Button id={index} onClick={(e) => this.onClick(e)}>{item.data}</Button>
              {this.state.show ? (
                <CropComponent title={item.data} opts={item.opts} data={item.child} />
              ) : null}
            </div>
          );
        });
        return items;  
      } 
    render() {
        var opts = this.props.opts;
        return (
          <div>
            {this.renderTabs()}
          </div>
        )} 
    }

    export default Main;

这是我的 CropComponent :

 class CropComponent extends Component {
  constructor(props) {
    super(props);
    this.state = {

    };
  }

  render() {   
    return (
        <div>hello {this.props.data}</div>      
    );
  }
}

export default CropComponent;

这是我的按钮单击按钮时如何显示其相关组件并在重新单击同一按钮时将其隐藏?

标签

4

1 回答 1

1

保持show初始值为-1的状态。向 onClick 提供事件和索引。在onClick做 setState 的showas index

检查是否show === index并渲染相应的组件。

像这样

this.state = {
    show: -1
}  

onClick(e,index) {
    e.preventDefault()
    this.setState({ show: show===index? -1 :  index});   
}  


__.forEach(child, (item, index) => {
    items.push(
      <div>
        <Button id={index} onClick={(e) => this.onClick(e,index)}>{item.data}</Button>
        {this.state.show === index ? (
          <CropComponent title={item.data} opts={item.opts} data={item.child} />
        ) : null}
      </div>
    );
});

编辑: 根据@Tony Nguyen 的有用评论更新了答案

于 2020-06-10T14:48:35.623 回答