javascript - 在反应中调用作为道具传递的方法
问题描述
我的父元素中有方法,di 将其作为道具传递;像这样:
<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
接收委托的组件中的this
与函数中使用的不同。传递时您必须绑定它。
<NavBar retrieveList={this.retrieveList.bind(this)}/>
然后你可以在你的函数体中调用它,如下所示。
this.props.retrieveList();
推荐阅读
- recaptcha - Recaptcha 总是第一次遇到多个失败事件
- python - 将文本文件中的特定列制作成列表
- mocking - Spock 存根匹配部分参数
- python - 在 for 循环中更新 MySQL 表并同时从另一个 Python 文件中更新的 MySQL 表中提取此数据
- apache-beam - 如何在 Apache BEAM 中使用 withDynamicRead 和 KafkaIO
- c++ - 在映射中插入 thread::id 和类实例
- angular - SVG - 线性渐变 - 停止偏移/停止颜色属性 Angular
- logstash-grok - Grok 模式语义
- assembly - 使用 = 运算符或从文字池加载数据有什么区别?
- html - 并排显示 DIV