簡體   English   中英

未定義不是對象React Native

[英]undefined is not object React Native

我越來越清楚,當嘗試從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);

    }

有人知道如何解決嗎?

問題是您在使用this.onBack時會丟失上下文

您需要確保在組件上下文中調用this.onBack ,並且可以通過以下兩種方法之一進行操作:

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM