javascript - undefined 不是 React Native 对象

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

当我尝试从 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);

    }

有人知道如何解决这个问题吗?

最佳答案

问题是使用 this.onBack 时您会丢失上下文

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

  • 使用箭头函数:this.props.navigation.setParams({goBack: (e) => this.onBack(e)});

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

关于javascript - undefined 不是 React Native 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50487069/

相关文章:

ios - React Native 中具有固定宽度和可用空间的灵活布局

php - 网页/应用程序的库/悬停或单击菜单示例,从哪里开始?

javascript - react Hook : useEffect for modal event listener

javascript - 如何在 reactjs 中有一个粘性导航栏

angular - 如何创建贴纸应用程序并将其发送到 WhatsApp 或任何使用 JS 框架(如 ionic 或 React Native)的信使?

android - 如果设备被锁定,定时器完成后的通知 - React Native EXPO?

javascript - 为不受支持的浏览器将 SVG 图像转换为 png - 回退 - modernizr.js(?)

javascript - 修改减少es6

当覆盖设置为隐藏时,JavaScript 更新消失

reactjs - 使用 React.cloneElement 和 render prop 将 ref 传递给类组件