javascript - 如何使用 'this.pros.function' 调用在组件上下文中运行的函数?
问题描述
我想写一个 npm 包somePackage
。现在我编写了另一个代码来使用这个包。如果自定义代码写的functionA
,我会使用自己functionA
,否则我会使用functionA
这个包中的。但我未能使自定义functionA
在somePackage
上下文中运行。
class somePackage extends React.Component{
constructor(props)
{
super(props);
}
functionA () {
if (this.props.functionA)
this.props.functionA.call(this);
...some other codes...
}
}
class customComponent extends React.Component{
...
functionA(){
this.setState(state => ({ tags: [...this.state.tags, tag] }));
}
render(){
return (<somePackage/>)
}
}
我希望它this.props.functionA.call(this)
可以this.props.functionA
在somePackage
上下文中运行,但它实际上是在customComponent
上下文中运行的。该this
指针仍然指向 customComponent。
解决方案
请改用箭头函数语法:
functionA = () => { // arrow function allows "this" to refer to the class when the function is called
if (this.props.functionA)
this.props.functionA.call(this);
...some other codes...
}
推荐阅读
- ssl - 但是,托管具有活动 SSL 证书的网站,导航到 www.example.com 会导致我访问 Http 而不是 Https
- javascript - 需要帮助使用某种类型的样式与反应
- android - Firebase 文档未删除
- c++ - 将二维数组中的符号分成 2 组
- javascript - 包含数组对象的 JSON - ajax 调用结果为空
- r - 对行子集执行计算
- python-3.x - 在python中,如何组合两个形状相似但不完全相同的np数组
- sql - 如何从今天开始从 DB2 获取过去 7 天(1 周)的记录
- c - 在本地测试 TCP/IP 服务器
- java - 无法从片段内部刷新 recyclveiw?