【问题标题】:Call a method passed as a prop in react在反应中调用作为道具传递的方法
【发布时间】:2020-11-27 19:27:20
【问题描述】:

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

<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);
      });
  }

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

【问题讨论】:

  • 你能分享一下this.retrieveList 传递给NavBar 时的含义吗?似乎它可能不是一个函数。
  • retrieveList() { StaffDataService.getAll() .then(response =&gt; { this.setState({ staffWithBasics: response.data, filteredItems: response.data, }); }) .catch(e =&gt; { console.log(e); }); }
  • 你试过了吗:&lt;NavBar retrieveList={this.retrieveList.bind(this)}/&gt;,然后在你的方法体中使用this.props.retrieveList();调用它

标签: javascript reactjs react-native methods react-router


【解决方案1】:

这是因为接收委托的组件中的this 与函数中使用的this 不同。传下去的时候一定要绑定。

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

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

this.props.retrieveList();

【讨论】:

  • 成功了,非常感谢。实际上我已经在我的父组件中绑定了retrieveList,但是当作为“prop”发送时,添加.bind解决了问题。
猜你喜欢
  • 2017-08-30
  • 2019-06-28
  • 1970-01-01
  • 2017-01-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-28
相关资源
最近更新 更多