简体   繁体   中英

Proper way to set state between two react components

I have a component for a Navbar and a component for a Sidebar . The sidebar component has a state variable that decides whether or not it should be open. Here is what I have.

export default class Sidebar extends Component {
  constructor() {
    super(...arguments);
    this.state = { open: false };
  }
  toggle() {
    this.setState({ open: !this.state.open });
  }
  render() {
    return (
      <LeftNav open={this.state.open}>
        <MenuItem
          onClick={this.toggle.bind(this)}
          primaryText="Close"
          leftIcon={<CloseIcon/>}
        />
      </LeftNav>
    )
  }
}

The problem I am having is in accessing the toggle functionality from a separate component, the Navbar.

<AppBar
  title="Navbar"
  iconElementLeft={
    <IconButton onClick={}>  // want to enable clicking here to close sidebar component
      <MenuIcon>
    </IconButton>
  }
/>

What I am wondering is, what is the best practice to set the state of separate components?

You have entered into the exciting realm of "data flow".

One way to implement this is to have some sort of centralized object that listens for events and dispatches information to other components. In other words, your NavBar handler can dispatch what many frameworks refer to as an "action" with some information, and then other components can re-render based on the information from that event.

A library that's gaining some popularity is redux if you're into a pre-packaged solution for this kind of thing. If nothing else, it'll help you gain some insight into how other people are currently doing this type of thing.

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