2

当我试图从 navigationOptions 的上下文中调用this.refs时,我知道错误 undefined is not an object 。

如果我用代码解释会更好:

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

    }

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

4

1 回答 1

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

于 2018-05-23T11:26:38.723 回答