reactnative 使用react-navigation通过props获取navigation,然后切换页面
但是使用tabBar组件,tabBar页面中无法通过props获取navigation
在这些特殊界面使用导航的
1.在函数组件中
import {NavigationContext} from "@react-navigation/native";
const Index=()=>{
// 获取导航器
const navigation1 = React.useContext(NavigationContext);
let click=()=>{
navigation1.navigate('AddLand')
}
return (
<View style={{flex:1}}>
<TouchableOpacity style={{position:'relative',top:-40,borderRadius:10,overflow:'hidden'}} onPress={click}>
<Image style={{width:200,height:75,resizeMode:'stretch'}} source={require('../../assets/img/land/options.png')}></Image>
</TouchableOpacity>
</View>
)
}
2.在类组件
import {NavigationContext} from "@react-navigation/native";
class Index extends React.Component{
constructor(props) {
super(props);
}
static contextType = NavigationContext;
render() {
let back=()=>{
this.context.goBack()
}
return <View>
<View style={[styles.nav,{ backgroundColor:this.state.navBgColor}]}>
<Text onPress={back} style={{color:this.state.backcolor}}>{this.state.backTitle}</Text>
</View>;
}
}
注意:在类组件中必须使用
static contextType = NavigationContext;
this.context.goBack()