You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React Native中如何从TabView组件向Selected组件传递Props?

如何从TabView向动态生成的Selected组件传递Props

在React Navigation的动态Tab场景下,你可以通过将路由的screen配置为返回组件的函数来传递自定义props,具体实现如下:

核心修改点

在你生成Tab路由配置的reduce方法中,不要直接将screen设为Selected,而是用一个函数返回Selected组件实例,同时把React Navigation的导航props和你的自定义props一起传递进去:

tabs = tabs.reduce((val, tab) => {
  val[tab] = { 
    // 通过函数包装组件,传递自定义props
    screen: (navProps) => <Selected {...navProps} type={tab} /> 
  }
  return val
}, {})

原理说明

React Navigation允许screen属性接收一个函数,这个函数会自动接收导航相关的props(比如navigation、route等)。我们通过解构navProps把这些默认props传递给Selected,再追加自定义的type(这里用当前tab的名称作为值),就能实现从TabView向每个Selected组件传递独有的props。

验证效果

修改后,你可以在Selected组件中直接访问传递过来的props:

export class Selected extends Component {
  constructor(props){
    super(props);
    this.state = {
      screen: '',
      screenType: this.props.type // 现在能正确获取到传递的type值
    }
  }

  render() {
    const { navigation } = this.props;
    return (
      <View style={{flex: 1}}>
        <NavigationEvents onWillFocus={this.screenIs} />
        <Text>当前标签类型: {this.props.type}</Text>
        <Text>当前屏幕: {this.state.screen}</Text>
      </View>
    );
  }
}

扩展:传递公共props

如果需要给所有Selected组件传递相同的公共props,只需要在函数中统一添加即可:

screen: (navProps) => <Selected {...navProps} type={tab} commonProp="所有标签共享的值" />

这种方式是React Navigation中给路由组件传递自定义props的标准方案,完美适配动态生成Tab的场景,不会破坏原有导航逻辑。

内容的提问来源于stack exchange,提问作者Shubham Bisht

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 07:09:11