以编程方式反应导航更改选项卡顺序

TIJ*_*TIJ 6 reactjs react-native redux react-navigation

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

Car*_*o G 0

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

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);
Run Code Online (Sandbox Code Playgroud)