首页 > 解决方案 > 在反应中调用作为道具传递的方法

问题描述

我的父元素中有方法,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);
      });
  }

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

标签: javascriptreactjsreact-nativemethodsreact-router

解决方案


发生这种情况是因为this接收委托的组件中的this与函数中使用的不同。传递时您必须绑定它。

<NavBar retrieveList={this.retrieveList.bind(this)}/>

然后你可以在你的函数体中调用它,如下所示。

this.props.retrieveList();

推荐阅读