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

sam*_*b90 10 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>
        );
    }
};
Run Code Online (Sandbox Code Playgroud)

我一直收到错误消息:

"undefined is not an object ("evaluating this.props.nav") 
Run Code Online (Sandbox Code Playgroud)

当"onPress"调用"this.about"时.我在render函数中放置了一个console.log,我可以看到this.props.nav包含一个值.问题出现在about()函数中,我不知道为什么.

任何建议都会很棒吗?

谢谢

小智 21

我无法确定,但这看起来像是一个Javascript this绑定问题.在ReactJS中,使用ES6类语法定义的组件不会自动绑定 this,因此您会被Javascript的规则this所咬,这些规则会根据函数的调用方式改变值.

.bind设置按钮处理程序时可能需要明确使用:

<Text onPress={this.about.bind(this)} style={styles.item}>About</Text>
Run Code Online (Sandbox Code Playgroud)

因此,thisabout()函数中将与设置处理程序thisrender()函数中的函数相同.

我找到了一个repo,它显示了解决相同问题的其他方法,比如在构造函数中绑定或者为处理程序使用"Fat-arrow"函数.

我的经验是使用React for web,我不确定React Native在这方面是否有所不同.


Nic*_*cko 6

您还可以重新绑定方法声明本身,这样就不必记住调用.bind(this)JSX。如果您有许多调用相同功能的按钮,这将很有用。

例如:

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>
Run Code Online (Sandbox Code Playgroud)