首页 文章

如何从子组件更改父组件的状态?

提问于
浏览 1181 次
1

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

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

2 回答

  • 2

    这里是's how you can do it. And here'的工作示例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属性 .

  • 4

    您可以在父组件上创建一个更新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)} />
        )
      }
    }
    

相关问题