首页 > 解决方案 > 添加自定义按钮以响应导航底部TabNavigator?

问题描述

我正在尝试创建一个选项卡导航器,其中包含一个不链接到选项卡组件的按钮,而是在链接到堆栈导航器中的页面的 onPress 效果上。

这是我需要创建以供参考的图片:

在此处输入图像描述

我遇到了这篇文章(How to add Button to a BottomTabNavigator on React Native?),它似乎有一个类似的目标,但是当我尝试实现这个解决方案时,它仍在寻找一个组件(错误)。

有没有好的方法来做到这一点?我的导航器看起来像这样:

    <NavigationContainer>
      <Tab.Navigator>
        <Tab.Screen name="Home" component={HomeScreen} />
        <Tab.Screen name="Discover" component={DiscoverScreen} />

//need custom button component here

        <Tab.Screen name="Notifications" component={NotificationsScreen} />
        <Tab.Screen name="Profile" component={ProfileScreen} />


      </Tab.Navigator>
    </NavigationContainer>

标签: javascriptreactjsreact-nativereact-navigation

解决方案


首先在您的 Tab.Navigator 中创建一个自定义按钮组件

<NavigationContainer>
  <Tab.Navigator>
    <Tab.Screen name="Home" component={HomeScreen} />
    <Tab.Screen name="Discover" component={DiscoverScreen} />

    <Tab.Screen name="stackScreens" component= {stackScreens} />  //your custom component

    <Tab.Screen name="Notifications" component={NotificationsScreen} />
    <Tab.Screen name="Profile" component={ProfileScreen} />
  <NavigationContainer>
<Tab.Navigator>

当用户点击中间按钮时,他们将重定向到堆叠的屏幕。现在您必须创建一个组件,该组件将使用堆栈导航器来显示多个堆栈屏幕。这是我们的stackScreens组件的代码片段

const plusStack = createStackNavigator();  // creating stack navigator instance

function stackScreens() {
  return (
    <plusStack.Navigator>
      <plusStack.Screen name="stackScreen1" component={stackScreen1} />
      <plusStack.Screen name="stackScreen2" component={stackScreen2} />
    </plusStack.Navigator>
  );
}

function stackScreen2() {
  return (
    <View style={{ flex: 1, justifyContent: 'center',  alignItems: 'center' }}>
      <Text>stackScreen2</Text>
    </View>
  );
}
function stackScreen1({ navigation }) {
  return (
    <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
      <Text>plus screen</Text>
      <Button
        title="Go to stackScreen2"
        onPress={() => navigation.navigate('stackScreen2')}
      />
    </View>
  );
}

这里是小吃


推荐阅读