如何在TabNavigator的子标签页中访问传入的Props?
嘿,我来帮你解决这个问题!你现在是想把父组件传给TabNavigator的thisThing属性拿到子标签页里用对吧?下面给你几个可行的方案,根据你的React Navigation版本来选就行:
方案一:适合旧版React Navigation(v4及更早)—— 使用screenProps
你现在直接给<TabNavigation>传属性的方式不对,旧版导航器需要把自定义属性放到screenProps这个统一的对象里传递:
render() { var nearbyLocations = this.props.locationsNearby; return( // 把自定义属性包进screenProps里 <TabNavigation screenProps={{ thisThing: "thisThingValue" }} /> ) }
之后在子页面(比如Nearby组件)里,就可以通过this.props.screenProps来访问这个值:
// 在Nearby组件的方法中 componentDidMount() { console.log(this.props.screenProps.thisThing); // 输出"thisThingValue" }
方案二:适合新版React Navigation(v5+)—— 使用initialParams或动态传参
新版导航器更推荐用路由参数来传递数据,有两种方式:
方式A:定义TabNavigator时直接配置初始参数
如果这个属性是固定值,你可以在定义TabNavigator的时候,给目标页面配置initialParams:
var TabNavigation = createBottomTabNavigator({ NearbyScreen: { screen: Nearby, initialParams: { thisThing: "thisThingValue" } // 直接在这里传入参数 }, FindScreen:{ screen: LandmarkNavigation }, NotificationScreen:{ screen: Notifications }, MyProfile:{ screen: MyProfile } })
然后在Nearby组件里,通过route.params获取:
// 类组件写法 class Nearby extends React.Component { render() { console.log(this.props.route.params.thisThing); return <View>{/* ... */}</View>; } } // 函数式组件写法 function Nearby({ route }) { console.log(route.params.thisThing); return <View>{/* ... */}</View>; }
方式B:从父组件动态传递参数
如果thisThing的值是依赖父组件的props动态生成的,你可以通过导航器的navigation.setParams方法,或者更灵活的是用React Context(看方案三)。
方案三:全局传递—— 使用React Context
如果多个子页面都需要访问这个属性,或者属性需要动态更新,用React Context是最方便的:
- 先创建一个Context:
import React, { createContext, useContext } from 'react'; // 创建上下文 const AppContext = createContext();
- 在父组件中用Provider包裹TabNavigator,把属性作为value传递:
render() { var nearbyLocations = this.props.locationsNearby; return( <AppContext.Provider value={{ thisThing: "thisThingValue" }}> <TabNavigation /> </AppContext.Provider> ) }
- 在任意子页面中访问这个值:
// 类组件写法 class Nearby extends React.Component { // 声明使用的Context static contextType = AppContext; componentDidMount() { console.log(this.context.thisThing); // 输出"thisThingValue" } render() { return <View>{/* ... */}</View>; } } // 函数式组件写法 function Nearby() { const { thisThing } = useContext(AppContext); console.log(thisThing); return <View>{/* ... */}</View>; }
内容的提问来源于stack exchange,提问作者user6536559
相关产品推荐
相关产品推荐

