reactjs - 将 onPress 处理程序附加到在组件外部构造的 Text
问题描述
我有我的组件类,我们称之为MyComponent
。它有一个复杂的执行逻辑,但这是省略了不必要的代码片段后的样子:
class MyComponent extends Component {
justWarn(input) {
console.warn(input);
// do something with `this` as well
}
render() {
return (
<View>
{this.props.myText}
</View>
);
}
}
const mapStateToProps = () => {
// Call the getText function here
return {
myText: getText()
};
}
export default connect(mapStateToProps)(MyComponent);
现在该函数getText
在其他文件中定义,如下所示:
function getText() {
// Let's assume it returns hard-coded value for the sake of brevity
return (
<Text>
<Text>I am the first part</Text>
<Text
onPress={function(){
// I want to call the function that is defined inside MyComponent
// since this Text will eventually be a part of MyComponent
this.justWarn('Warn me in the yellow box')
}}
>I am the clickable part
</Text>
</Text>
);
}
当我尝试调用上面justWarn
定义的MyComponent
from 中Text
定义的方法时,我得到一个错误undefined is not a function, evaluating this.justWarn
。
我的问题是,我没有使用箭头函数,因此this
在我声明处理程序时不受约束onPress
。它实际上是在什么时候Text
被调用的MyComponent
,所以不应该this
对应MyComponent
并且上面的代码应该可以正常工作吗?
我在这里做错了什么?有没有办法通过将getText
和MyComponent
拆分为两个文件来实现这一点?
谢谢。
解决方案
问题是getText
没有this
上下文,因此您需要以某种方式绑定它以获取上下文。
实现这一目标的一种方法是MyComponent
像这样进行更改-
class MyComponent extends Component {
justWarn(input) {
console.warn(input);
alert(input)
// do something with `this` as well
}
render() {
const myText = this.props.myText.bind(this)
return (
<View>
<Text>something should render</Text>
{myText()}
</View>
);
}
}
const mapStateToProps = () => {
// Call the getText function here
return {
myText: getText
};
}
export default connect(mapStateToProps)(MyComponent);
...
然后像这样在 onPress 事件处理程序中使用箭头函数 -
function getText() {
// Let's assume it returns hard-coded value for the sake of brevity
return (
<Text>
<Text>I am the first part</Text>
<Text
onPress={() => {this.justWarn('Warn me in the yellow box')}}
>I am the clickable part
</Text>
</Text>
);
}
...
希望能帮助到你。
推荐阅读
- sql-server - 我创建并运行了一个 sqlserver 容器,我停止了它,我不知道如何再次运行它?
- r - 如何绑定两个数据框的行,使 ID 列中具有相同值的行彼此相邻
- ios - 如何将 UIView 作为 SuperView(背景视图)添加到已存在的带有约束的 UI 元素
- freemarker - Freemarker修剪正确的空间不起作用
- android - 在 webview 表单中从键盘隐藏表情符号
- python-3.x - 使用 python 请求发布具有多个文件上传的多部分表单
- cmake - CMake 编译选项仅用于编译测试
- google-api - API 发现服务仅在 BigQuery 中返回错误
- java - 在不知道名字的情况下绑定参数查询
- javascript - 从html文件中的按钮从另一个文件中触发JS函数