undefined 不是对象 React Native
undefined is not object React Native
我在尝试从导航选项的上下文中调用 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
,您可以通过以下任一方式执行此操作:
使用arrow functions
:this.props.navigation.setParams({goBack: (e) => this.onBack(e)});
将 this
绑定到您的函数:this.props.navigation.setParams({goBack: this.onBack.bind(this)});
我在尝试从导航选项的上下文中调用 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
,您可以通过以下任一方式执行此操作:
使用
arrow functions
:this.props.navigation.setParams({goBack: (e) => this.onBack(e)});
将
this
绑定到您的函数:this.props.navigation.setParams({goBack: this.onBack.bind(this)});