【问题标题】:Callback function from child component in react来自子组件的回调函数在反应
【发布时间】:2018-09-19 06:26:33
【问题描述】:

这里我有父子通信,效果很好。

 var ParentComponent = React.createClass({
        update: function() {
            console.log("updated!");
        },
        render: function() {
          <ChildComponent callBack={this.update} />
        }
    })

    var ChildComponent = React.createClass({
    preupdate: function() {
        console.log("pre update done!");
    },
    render: function() {
      <button onClick={this.props.callback}>click to update parent</button>
    }
})

在按钮 Onclick 事件期间调用父回调方法之前,如何在子组件中调用 preupdate 函数。

【问题讨论】:

    标签: reactjs


    【解决方案1】:

    对于 react hooks 可以参考下面的解决方案。

    • 父类

      function ProfilePage() {
      
      const successCallBackData = (data) => {
         console.log(data)// can get callback data here
      }
      return (
          <>
            <AlertModal callBack={successCallBackData} /> 
          </>
      );
      }
      
      export default ProfilePage;
      
    • 子类

      const AlertModal = (props) =>{
      
      const goBack = () => {
          props.callBack('hello');// can pass callback data here
      }
      return (
          <>
            <div>
            <Button className="btn-round" color="danger"   onClick={goBack}>
              Go Back
                  </Button>
            </div>
          </>
      );
      }
      
      export default AlertModal;
      

    【讨论】:

      【解决方案2】:

      您可以调用 preupdate 函数作为点击处理程序。然后当它完成后,它可以调用回调。

      var ParentComponent = React.createClass({
          update: function() {
              console.log("updated!");
          },
          render: function() {
            <ChildComponent callBack={this.update} />
          }
      })
      
      var ChildComponent = React.createClass({
          preupdate: function() {
              console.log("pre update done!");
              this.props.callback()
          },
          render: function() {
              <button onClick={this.preupdate.bind(this)}>click to update parent</button>
          }
      })
      

      【讨论】:

        【解决方案3】:

        使用以下内容:

        <button onClick={(args)=>{this.preupdate(args);this.props.callback(args);}>click to update parent</button>
        

        您还需要像这样重新定义预更新函数:

        preupdate: ()=> {
                console.log("pre update done!");
            }
        

        以便在调用此方法时保留this 上下文。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2021-02-08
          • 2019-02-01
          • 1970-01-01
          • 2015-12-06
          • 2020-08-20
          • 1970-01-01
          • 2019-10-13
          相关资源
          最近更新 更多