简体   繁体   中英

ReactJs connect 2 child components

如果在 Angular 2 中可以将两个子组件相互连接起来,它如何在 react js 中进行管理?

A) You can use Redux or Flux to keep a single state for the whole application, which you will be able to access from any component that you decide to connect with this state, called the Store.

You can read more about this in https://github.com/reduxjs/redux .

B) If both components are siblings, and the state you are trying to share is not something that you would care about in the rest of the application, you can pass the state from the parent to both children, as props, and also pass a function that allows the children to set the parent's state.

For example:

class Parent extends Component {
  state = {
    something: '',
  }

  changeSomething = (e) => {
    this.setState({
      something: e.target.value,
    })
  }

  render() {
    const { something, changeSomething } = this.state;
    return(
      <div>
        <ChildrenA
          something={something}
          changeSomething={changeSomething}
        >
        <ChildrenB
          something={something}
          changeSomething={changeSomething}
        >
      </div>
    );
}

Now both children have access to this.props.something and this.props.changeSomething and they can both change the parent's state and both will see the changes.

Hope it helps

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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