react-native – React Native从内部函数访问this.prop

我有以下代码
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在这方面是否有所不同.

相关文章

一、前言 在组件方面react和Vue一样的,核心思想玩的就是组件...
前言: 前段时间学习完react后,刚好就接到公司一个react项目...
前言: 最近收到组长通知我们项目组后面新开的项目准备统一技...
react 中的高阶组件主要是对于 hooks 之前的类组件来说的,如...
我们上一节了解了组件的更新机制,但是只是停留在表层上,例...
我们上一节了解了 react 的虚拟 dom 的格式,如何把虚拟 dom...