Call a method passed as a prop in react

a 夏天 提交于 2021-02-20 19:10:12

问题


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?


回答1:


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


来源:https://stackoverflow.com/questions/63302124/call-a-method-passed-as-a-prop-in-react

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!