繁体   English   中英

React处理组件之间的交互状态

[英]React Handle interaction state between components

我有一个显示元素onClick的简单组件:

    class MyComponent extends React.Component {

       state = {
        isVisible : false
       }

     render() {
      const { isVisble } = this.state
      return(
      <div>
       {isVisble ? 
        <div onClick={() => this.setState({isVisble: false})}>Hide</div> : 
        <div onClick={() => this.setState({isVisble: true})}>Show</div>}
      </div>
     )
    }
}

我在其他组件中使用此组件三次:

class MySuperComponent extends React.Component {     
 render() {
  return(
  <div>
   <MyComponent /> 
   <MyComponent /> 
   <MyComponent /> 
  </div>
  )}
}

如果其中一个isVisible为true,我需要为所有其他组件传递isVisible为false

怎么做 ?

谢谢

您应该控制组件,因此将isVisble移动到props,然后从MySuperComponent分配它。

同时向MyComponent传递一个回调,以便它可以通知父级是否要更改状态。

您需要一些数据结构来存储这些状态。

https://codepen.io/mazhuravlev/pen/qxRGzE

class MySuperComponent extends React.Component {
    constructor(props) {
        super(props);
        this.state = {children: [true, true, true]};
        this.toggle = this.toggle.bind(this);
    }

    render() {
        return (
            <div>
                {this.state.children.map((v, i) => <MyComponent visible={v} toggle={() => this.toggle(i)}/>)}
            </div>
        )
    }

    toggle(index) {
        this.setState({children: this.state.children.map((v, i) => i !== index)});
    }
}

class MyComponent extends React.Component {
    render() {
        const text = this.props.visible ? 'visible' : 'hidden';
        return (<div onClick={this.props.toggle}>{text}</div>);
    }
}


React.render(<MySuperComponent/>, document.getElementById('app'));

你可以在这里查看你的代码,这是你想要的。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM