简体   繁体   English

在两个反应组件之间设置状态的正确方法

[英]Proper way to set state between two react components

I have a component for a Navbar and a component for a Sidebar . 我有一个Navbar组件和一个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. 我遇到的问题是从单独的组件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. 换句话说,您的NavBar处理程序可以使用某些信息来分派许多框架称为“动作”的内容,然后其他组件可以基于该事件中的信息重新呈现。

A library that's gaining some popularity is redux if you're into a pre-packaged solution for this kind of thing. 如果您正在为这种事情提供预打包的解决方案,那么正在流行的库就是redux If nothing else, it'll help you gain some insight into how other people are currently doing this type of thing. 如果没有别的,它会帮助您了解其他人当前在做这种事情的方式。

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

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