【问题标题】:How can I change the state of a parent component from a child component?如何从子组件更改父组件的状态?
【发布时间】:2016-12-21 05:29:27
【问题描述】:

我有一个具有布尔状态属性“showModal”的父组件。当 showModal 为 true 时,我会渲染子组件“Modal”。这个 Modal 有一个关闭按钮,它应该将“showModal”属性切换回 false。 “showModal”作为 props 传递给子 Modal 组件,但由于 props 在 React 中是不可变的,我还没有找到正确的更改模式。

我可以利用某种双向数据绑定吗?处理这个问题的最佳方法是什么?

【问题讨论】:

    标签: reactjs


    【解决方案1】:

    您可以这样做。这是 JSBin 的工作示例:https://jsbin.com/yixano/2/edit?html,js,output

    var ModalParent = React.createClass({
      getInitialState: function() {
        return {showModal: false};
      },
    
      toggleShowModal: function() {
        this.setState({showModal: !this.state.showModal});
      },
    
      render: function() {
        return (
          <div>
            <button type="button" onClick={this.toggleShowModal.bind(this)}>Toggle Show Modal</button>
            {this.state.showModal ? 
                <Modal onModalClose={this.toggleShowModal.bind(this)}/> : 
                <div></div>}
            <h4>State is: </h4>
            <pre>{JSON.stringify(this.state, null, 2)}</pre>
          </div>);
      }
    });
    
    var Modal = React.createClass({
      render: function(){
        return <div><button type="buton" onClick={this.props.onModalClose}>Close</button></div>
      }
    });
    
    ReactDOM.render(<ModalParent/>, document.getElementById("app"));
    

    这里的想法是将 ModalParent 上的函数的引用传递给 Modal,以便可以根据子项中的操作更改父项中的状态。

    如您所见,孩子有一个名为“onModalClose”的道具,它需要一个在单击关闭按钮时调用的函数引用。在父级中,我们将相应的 toggleShowModal 绑定到这个 onModalClose 属性。

    【讨论】:

    • 这是我一直在寻找的答案。谢谢!
    【解决方案2】:

    您可以在父组件上创建一个方法来更新 showModal 的状态,并将其作为回调传递给 props 上的子组件。在子组件上定义一个函数,执行传递给 props 的函数。在关闭模型的“x”上设置一个 onClick 侦听器,因此将调用子函数,执行父函数上的函数。这应该会更新父级的状态并导致两者重新渲染。

    class MyParent extends Component {
      toggleShowModal(){
        this.setState({showModal: !this.state.showModal})
      }
    
      render(){
      return (
        <Modal toggleShowModalCallback={this.toggleShowModal.bind(this)} />
       )
      }
    

    }

    class Modal extends Component {
    
      updateParent(){
        this.props.toggleShowModalCallback()
      }
    
      render(){
        return(
        <CloseModalButton onClick={this.updateParent.bind(this)} />
        )
      }
    }
    

    【讨论】:

    • Modal 类不需要 updateParent 方法。您可以只使用 this.props.toggleShowModalCallback。请参阅下面的答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-12-26
    • 1970-01-01
    • 2019-12-23
    • 2017-09-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多