问题
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