首页 文章

使用React Navigation(React Native)进行条件路由

提问于
浏览
0

构建一个React Native应用程序,我会将用户发送到下一个屏幕依赖于初始选择屏幕的状态 . 因此,如果选择了1个项目,则应将用户带到单个屏幕 . 如果超过1,则为多屏 .

如您所见,我制作了自定义headerLeft和headerRight组件 . 我宁愿以这种方式保持路由,但不知何故将初始状态添加到此上下文中 . 有办法吗?

如果我可以以某种方式将routes.js文件中的导航选项解耦并将它们放入Screen组件本身,那将是非常棒的 . 但是根据我的研究,似乎navigationOptions不能直接访问状态 .

这是相关的代码(routes.js):

export default StackNavigator(
  {
    Select: {
      screen: Select,
      navigationOptions: ({ navigation }) => ({
        headerLeft: <View />,
        headerRight: (
          <HeaderRight
            navigation={navigation}
            destination=""
            showIcon
          />
        )
      })
    },
    Single: {
      screen: Single,
      navigationOptions: ({ navigation }) => ({
        headerLeft: (
          <HeaderLeft navigation={navigation} destination="back" showIcon />
        ),
        headerRight: (
          <HeaderRight navigation={navigation} destination="SingleSecond" />
        )
      })
    },
    Multiple: {
      screen: Multiple,
      navigationOptions: ({ navigation }) => ({
        headerLeft: <HeaderLeft navigation={navigation} destination="back" />,
        headerRight: (
          <HeaderRight navigation={navigation} destination="MultipleSecond" />
        )
      })
    },
  },
  {
    headerMode: "float",
    navigationOptions: ({ navigation }) => ({
      title: `${navigation.state.routeName}`,
      headerStyle: { backgroundColor: "#000" },
      headerTitleStyle: {
        color: "#fff",
        textAlign: "center",
        alignSelf: "center"
      }
    })
  }
);

1 回答

  • 1

    您可以从组件中设置参数,这些参数可以从导航选项中访问 .

    this.props.navigation.setParams({ selectionState: "single" });
    this.props.navigation.setParams({ selectionState: "multiple" });
    

    你可以从导航选项中访问参数

    static navigationOptions = ({navigation}) => {
      let selected = navigation.state.params && navigation.state.params.selectionState;
      return {
        headerRight: ...
      };
    }
    

    我希望这可以满足您的需求,您需要在选择组件中的内容后设置参数 . 还有另一种动态设置初始状态的方法 .

    function getNavigation (selected = "single") {
      return StackNavigator({
        ...,
        { initialState = selected === "single" ? "Single" : "Multiple" }
      })
    }
    

    然后使用所选参数调用此方法以重置屏幕 .

相关问题