【发布时间】: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 => { this.setState({ staffWithBasics: response.data, filteredItems: response.data, }); }) .catch(e => { console.log(e); }); } -
你试过了吗:
<NavBar retrieveList={this.retrieveList.bind(this)}/>,然后在你的方法体中使用this.props.retrieveList();调用它
标签: javascript reactjs react-native methods react-router