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