我有以下代码:
module.exports = class Menu extends Component {
about() {
this.props.nav.push({
component: TestView,
title: 'Test View',
});
}
render() {
return (
<ScrollView
scrollsToTop={false}
style={styles.menu}
navigator={this.props.nav}>
<View style={styles.logoContainer}>
<Image
style={styles.logo}
source={{ uri, }}/>
</View>
<Text onPress={this.about} style={styles.item}>About</Text>
<Text style={styles.item}>Account</Text>
</ScrollView>
);
}
};
我不断收到错误消息:
"undefined is not an object ("evaluating this.props.nav")
当“onPress”调用“this.about”时。我在渲染函数中放置了一个 console.log,我可以看到 this.props.nav 包含一个值。问题出现在 about() 函数中,我不知道为什么。
有什么建议会很棒吗?
谢谢
最佳答案
我不能确定,但这看起来像 Javascript this
对我有约束力的问题。在使用 ES6 类语法定义的 ReactJS 组件中,请执行 not automatically bind this
, 所以你被 Javascript 的 rules that vary the value of this
取决于函数的调用方式。
您可能需要明确使用 .bind
设置按钮处理程序时:
<Text onPress={this.about.bind(this)} style={styles.item}>About</Text>
这样
this
在 about()
功能将与 this
相同在 render()
设置处理程序的函数。我找到了a repo它显示了解决相同问题的其他方法,例如在构造函数中绑定(bind)或使用 "Fat-arrow" functions为您的处理程序。
我的经验是使用 React for web,我不确定 React Native 在这方面是否有所不同。
关于react-native - React Native 从内部函数访问 this.prop,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35023879/