【问题标题】:Onclick an element that changes the state of another elementOnclick 改变另一个元素状态的元素
【发布时间】:2017-12-01 16:12:05
【问题描述】:

我正在尝试单击将触发更改列表顺序的排序图标。

为了更简单,假设您有一个按钮和另一个按钮,它们位于彼此不同的 div 上。

<div>
    //Button 1
    <button onclick={"some_click_handler"}>
</div>

<div>
    //Button 2
    <button>
        {this.state.someToggle ? true : false}
    </button>
</div>

【问题讨论】:

    标签: reactjs onclick event-handling setstate


    【解决方案1】:

    创建一个向按钮传递回调的组件,该回调将更新容器的状态,进而设置列表的道具。这在 React 中很常见,并且是组合模式如何工作的基础。如果您需要在两个组件之间共享数据,只需将它们放入容器中并将状态提升到父组件即可。这些组件通常称为容器,上面有一堆文档。

    这是一个很好的起点:https://reactjs.org/docs/lifting-state-up.html

    这样的……

    class Container extends React.Component {
      constructor(props) {
        super(props);
    
        // Don't forget to bind the handler to the correct context
        this.handleClick = this.handleClick.bind(this);
      }
    
      handleClick(sort) {
        this.setState({sort: sort});
      }
    
      render() {
        return (
          <Button handleClick={this.handleClick} />
          <List sort={this.state.sort} />
        )
      }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-08-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-30
      • 2018-06-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多