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

这篇博客介绍了如何在React Native应用中利用react-navigation库进行页面切换。在函数组件中,可以通过`useContext` hook获取NavigationContext来实现导航。而在类组件中,需要设置`static contextType = NavigationContext`,然后使用`this.context`调用导航方法,如`goBack()`。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值