react-native – React Native从内部函数访问this.prop
发布时间:2020-12-15 20:51:03 所属栏目:百科 来源:网络整理
导读:我有以下代码: 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}
我有以下代码:
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”时.我在render函数中放置了一个console.log,我可以看到this.props.nav包含一个值.问题出现在about()函数中,我不知道为什么. 有什么建议会很棒吗? 谢谢
我无法确定,但这看起来像Javascript这个绑定问题给我.在使用ES6类语法定义的ReactJS组件中执行
not automatically bind,因此您将被Javascript的
rules that vary the value of this 所困,具体取决于函数的调用方式.
在设置按钮处理程序时,您可能需要显式使用.bind: <Text onPress={this.about.bind(this)} style={styles.item}>About</Text> 因此,在about()函数中,这将与您设置处理程序的render()函数中的this相同. 我发现a repo显示了解决相同问题的其他方法,例如在构造函数中绑定或使用“Fat-arrow” functions处理程序. 我的经验是使用React for web,我不确定React Native在这方面是否有所不同. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |