The real interaction between the components

I have a simple component that shows an onClick element:

    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>
     )
    }
}

I use this component three times in another component:

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

I need to pass isVisible to false for all other components if one of them is IsVisible to true

How to do it?

thank

+4
source share
2 answers

You must have control of your component, so move isVisble to the details, and then assign it from MySuperComponent.

Also pass the MyComponent callback so that it can tell the parent if it wants to change state.

You need a data structure to store these states.

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'));
+2

, , .

0

Source: https://habr.com/ru/post/1693402/


All Articles