0
点赞
收藏
分享

微信扫一扫

reactnative 使用 react-navigation 在props没有接受navigation时,跳转界面

代码小姐 2022-03-18 阅读 76

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()

举报

相关推荐

0 条评论