undefined不是对象React Native

时间:2018-05-23 11:19:25

标签: javascript reactjs react-native react-navigation react-android

我越来越知道错误未定义在尝试从navigationOptions的上下文中调用 this.refs 时不是对象。

如果我用代码解释,那就更好了:

 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);

    }

任何人都知道如何解决这个问题?

1 个答案:

答案 0 :(得分:3)

问题是您在使用this.onBack

时会丢失上下文

您需要确保使用组件上下文调用this.onBack,并且可以通过以下任一方式执行此操作:

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

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