自定义优先渲染响应本机选项卡导航

时间:2020-09-15 17:34:28

标签: react-native react-router react-navigation-bottom-tab

有没有人知道如何设置初始路线,但没有关闭tab.screen反应导航? 我想在不从底部选项卡中选择焦点的情况下打开应用时将主屏幕设置为默认屏幕。

Like this image

,当我按浏览选项卡时,它会显示浏览页面。因此,当我单击“后退”按钮时,我也可以进入主屏幕。 enter image description here

1 个答案:

答案 0 :(得分:0)

它比您希望的要复杂得多,但是通过创建自定义标签栏组件,我已经有了一些工作:

const CustomTabBar = ({
  state,
  navigation,
  descriptors,
  screenHiddenInTabs,
}) => {
  return (
    <View
      style={{
        position: 'absolute',
        width: '100%',
        height: '100%',
      }}>
      <TouchableOpacity
        onPress={() => {
          navigation.navigate(state.routes[0].name);
        }}
        style={{
          position: 'absolute',
          height: 30,
          width: '100%',
          justifyContent: 'center',
          backgroundColor: 'white',
        }}>
        <Text style={{ padding: 5 }}>{'\u003c Back to Home'}</Text>
      </TouchableOpacity>
      <View
        style={{
          flexDirection: 'row',
          backgroundColor: 'white',
          height: 30,
          justifyContent: 'space-around',
          alignItems: 'center',
          position: 'absolute',
          width: '100%',
          bottom: 0,
        }}>
        {state.routes.map((route, index) => {
          const isFocused = state.index === index;

          const { options } = descriptors[route.key];
          const label =
            options.tabBarLabel !== undefined
              ? options.tabBarLabel
              : options.title !== undefined
              ? options.title
              : route.name;

          const onPress = () => {
            const event = navigation.emit({
              type: 'tabPress',
              target: route.key,
            });

            if (!isFocused && !event.defaultPrevented) {
              navigation.navigate(route.name);
            }
          };

          return route.name !== screenHiddenInTabs ? (
            <TouchableWithoutFeedback onPress={onPress}>
              <Text style={{ color: isFocused ? 'blue' : 'black' }}>
                {label}
              </Text>
            </TouchableWithoutFeedback>
          ) : null;
        })}
      </View>
    </View>
  );
};

// Pass the CustomTabBar component to the tabBar property
function YourTabs() {
  return (
    <Tab.Navigator
      tabBar={(props) => <CustomTabBar {...props} screenHiddenInTabs="Home" />}>
      <Tab.Screen name="Home" component={HomeScreen} />
      <Tab.Screen name="Browse" component={BrowseScreen} />
      <Tab.Screen name="Settings" component={SettingsScreen} />
    </Tab.Navigator>
  );
}

这里的想法是,我们不会在选项卡导航器中的路径的选项卡栏中显示选项卡,该路径名称等于我们添加的screenHiddenInTabs道具的值。

这样,如果我们将screenHiddenInTabs属性设置为"Home",则与该路线名称相关联的标签导航器中的屏幕会显示在第一个渲染中,但不会显示为标签栏。

此自定义标签栏还实现了顶部栏,该顶部栏使您可以返回到标签导航器的第一个屏幕,即您的情况下的主屏幕。

请注意,由于我使用绝对定位以便在顶部和按钮上放置一个条形,因此选项卡导航器内的屏幕可能需要额外的边距。 < / p>


我在以下答案中使用了自定义标签栏:Custom Tab Bar React Navigation 5作为我上面创建的自定义标签栏的模板。我建议您看一下那里的答案,因为我从该工具栏中剥离了一些功能,以使示例代码不那么冗长