【问题标题】:React Navigation change Tab order programmatically以编程方式反应导航更改选项卡顺序
【发布时间】:2017-10-29 01:48:42
【问题描述】:

我正在创建一个带有 react-native 的应用程序,并使用 react-navigation 进行路由。我知道我们最初可以在react-navigation 中更改标签顺序。但就我而言,我需要以编程方式更改标签顺序。有什么办法吗?

【问题讨论】:

    标签: reactjs react-native redux react-navigation


    【解决方案1】:

    下面是一个“几乎是伪代码”的例子。它至少应该让你朝着正确的方向前进。诀窍是使用“已连接”的主导航组件,该组件对 redux 存储中的更改做出反应(在我的情况下,我将选项卡顺序存储在“设置”减速器中)并强制重新渲染选项卡及其顺序,更改screenProps 属性通过 react-navigation 传递给每个导航器。然后有一个TabSelector 组件,它根据传递的道具返回正确的屏幕。如果我的意思不是很清楚,但英语不是我的主要语言,我很抱歉:)

    import Tab1 from 'app/components/Tab1';
    import Tab2 from  'app/components/Tab2';
    // ... all the imports for react-navigation
    
    const TabSelector = (props) => {
        switch(props.tab) {
            case 1:
                return <Tab1 {...props} />;
            case 2:
                return <Tab2 {...props} />;
        }
    };
    
    const Tabs = {
      PreferredTab: {
        screen: ({ screenProps }) => (
          <TabSelector tab={screenProps.firstTab} />
        ),
        navigationOptions: ({ screenProps }) => ({
          // write label and icon based on screenProps.firstTab
        })
      },
      OtherTab: {
        screen: ({ screenProps }) => (
          <TabSelector tab={screenProps.otherTab} />
        ),
        navigationOptions: ({ screenProps }) => ({
          // write label and icon based on screenProps.otherTab
        })
      },
      // other tabs...
    };
    
    const Navigator = createTabNavigator(Tabs, {
      initialRouteName: 'PreferredTab',
      // other options...
    });
    
    const WrappedNavigator = props => {
      // fetch tab index from redux state, for example
      const firstTab = useSelector(state => state.settings.firstTab);
      const otherTab = useSelector(state => state.settings.otherTab);
    
      return <Navigator screenProps={{ firstTab: firstTab, otherTab: otherTab }} {...props} />;
    };
    WrappedNavigator.router = Navigator.router;
    
    export default createAppContainer(WrappedNavigator);
    

    【讨论】:

      猜你喜欢
      • 2014-02-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-18
      • 2021-12-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多