我有以下代码:
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")
当&#34; onPress&#34;打电话&#34; this.about&#34;。我在render函数中放置了一个console.log,我可以看到this.props.nav包含一个值。问题出现在about()函数中,我不确定原因。
任何建议都会很棒?
由于
答案 0 :(得分:21)
我无法确定,但这对我来说似乎是一个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显示了解决同一问题的其他方法,例如在构造函数中绑定或使用"Fat-arrow" functions作为处理程序。
我的经验是使用React for web,我不确定React Native在这方面是否有所不同。
答案 1 :(得分:4)
您还可以重新绑定方法声明本身,这样您就不必记得在JSX中调用.bind(this)
。如果您有许多按钮调用相同的功能,这将非常有用。
例如:
class Menu extends Component {
constructor(props) {
super(props);
// Replace instance method with a new 'bound' version
this.about = this.about.bind(this);
}
// Elsewhere in JSX you don't need to remember to call .bind(this)
<Text onPress={this.about} style={styles.item}>About</Text>