在反应中调用作为道具传递的方法 [英] Call a method passed as a prop in react

查看:42
本文介绍了在反应中调用作为道具传递的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

i have method in my parent element, an d i passed it as a prop; like this:

<NavBar retrieveList={this.retrieveList}/>

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

and in my child component i can not able to call this method from another method body.

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. */
  }

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

By the way i have got constructor and bind;

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

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

what is my wrong with this code, how can i run this parent method?

推荐答案

出现这种情况是因为接收委托的组件中的 this 与组件中使用的 this 不同功能.传递时必须绑定.

This happens because the this in the component that receives the delegate is different from the this used in the function. You will have to bind it when passing it down.

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

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

And then you can call it in your function body as follows.

this.props.retrieveList();

这篇关于在反应中调用作为道具传递的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆