简体   繁体   English

未定义不是对象React Native

[英]undefined is not object React Native

I am getting well known error undefined is not an object when trying to call this.refs from the context of navigationOptions. 我越来越清楚,当尝试从navigationOptions的上下文调用this.refs时,未定义的错误不是对象。

Better if I explain with code: 如果我用代码解释更好:

 static navigationOptions = ({ navigation, screenProps }) => ({
        headerTitle: 'my app',
        title: 'my app',
        headerTitleStyle: {
            textAlign: "center",
            flex: 1,
        },
        headerLeft:
            <TouchableOpacity style={{padding: 15, marginLeft: 5}} onPress={() => { navigation.state.params.goBack(navigation.state.params.canGoBack) }}>
                {navigation.state.params.canGoBack ? <Text>back</Text>: <Text>close</Text>}
            </TouchableOpacity>,
    });


    componentDidMount() {
            this.props.navigation.setParams({goBack: this.onBack});
            this.props.navigation.setParams({canGoBack: this.state.canGoBack});
            Keyboard.dismiss();
        }

   onBack(canGoBack) {
        console.log(canGoBack);
        if(canGoBack){
            this.refs[WEBVIEW_REF].goBack(); // here is the error happening, somehow I can access this.refs.
        }
    }

    onNavigationStateChange(navState) {
        this.setState({
            canGoBack: navState.canGoBack
        });
        this.props.navigation.setParams({
            canGoBack: this.state.canGoBack,
        });
        console.log("some action happened: " + this.state.canGoBack);

    }

Anyone knows how to solve this? 有人知道如何解决吗?

The issue is that you are losing the context when using this.onBack 问题是您在使用this.onBack时会丢失上下文

You need to make sure that this.onBack is called with your component context, and you can do this by either: 您需要确保在组件上下文中调用this.onBack ,并且可以通过以下两种方法之一进行操作:

  • Using arrow functions : this.props.navigation.setParams({goBack: (e) => this.onBack(e)}); 使用arrow functionsthis.props.navigation.setParams({goBack: (e) => this.onBack(e)});

  • Bind this to your function: this.props.navigation.setParams({goBack: this.onBack.bind(this)}); this绑定到您的函数: this.props.navigation.setParams({goBack: this.onBack.bind(this)});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM