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

标签 react-native

我有以下代码:

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>

这样thisabout()功能将与 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/

相关文章:

ios - iOS 应用启动屏幕(闪屏)是必须的吗?

javascript - 将相同 Prop 和文本渲染到不同组件类型的 DRY React 方法

android - 运行react-native run-android 构建成功,但停留在启动应用程序

javascript - React Native - setTimeout 循环内

android - 生成 Release APK 时出错。错误 : Duplicate resources; AAPT: error: resource string/app_name not found

android - 是否可以在 react-native 中创建基于客户端工作空间的应用程序?

android - react native : catch volume buttons press (not for volume adjusting)

javascript - 我如何判断 Realm 是否已成功更新?

javascript - 如何删除React Native中的所有 Prop ?

javascript - react native : onPress on component doesn't function