在反应中调用作为道具传递的方法

我的父元素中有方法,di 将其作为道具传递;像这样:


<NavBar retrieveList={this.retrieveList}/>

在我的子组件中,我无法从另一个方法体调用此方法。


handleCloseModal () {

    window.$('#newHireModal').modal('hide');   /* this is working */

    console.log(this.props.retrieveList);     /* it gives method body, just to be sure props is coming here */

    this.props.retrieveList;   /*it gives "Expected an assignment or function call..." */

    this.props.retrieveList();   /*it gives "this.props.retrieveList is not a function" */

    return this.props.retrieveList;   /*it does nothing. no working, no error. */

  }

顺便说一句,我有构造函数和绑定;


constructor(props) {

    super(props);

    this.handleCloseModal = this.handleCloseModal.bind(this);

retrieveList() {

    StaffDataService.getAll()

      .then(response => {

        this.setState({

          staffWithBasics: response.data,

          filteredItems: response.data,

        });

      })

      .catch(e => {

        console.log(e);

      });

  }

这段代码有什么问题,我该如何运行这个父方法?


牛魔王的故事
浏览 83回答 1
1回答

开满天机

发生这种情况是因为this接收委托的组件中的this与函数中使用的不同。向下传递时,您必须绑定它。<NavBar&nbsp;retrieveList={this.retrieveList.bind(this)}/>然后你可以在你的函数体中调用它,如下所示。this.props.retrieveList();
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript