代码之家  ›  专栏  ›  技术社区  ›  Mizlul

未定义不是本地对象反应

  •  2
  • Mizlul  · 技术社区  · 7 年前

    我得到了众所周知的错误未定义不是一个对象时,试图调用 本.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 回复  |  直到 7 年前
        1
  •  3
  •   Hamza El Aoutar    7 年前

    问题是,当使用 this.onBack

    你要确保 这个。回首 是用组件上下文调用的,您可以通过以下两种方法之一进行调用:

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

    • 束缚 this 对于您的职能: this.props.navigation.setParams({goBack: this.onBack.bind(this)});