简体   繁体   English

在 React Native 中使用 React Navigation 有条件地渲染 header 右键

[英]Render header right button conditionally with React Navigation in React Native

I am trying to conditionally render the Entypo new-message icon in the right header based on a boolean variable (if the variable is true, then the icon will show up in the header).我正在尝试根据 boolean 变量有条件地在右侧 header 中呈现Entypo 新消息图标(如果该变量为真,则该图标将显示在标题中)。 Please see the minimum reproducible code below.请参阅下面的最小可重现代码。 Thanks in advance.提前致谢。

import { createBottomTabNavigator } from "@react-navigation/bottom-tabs";
import { Ionicons, MaterialCommunityIcons, Entypo } from "@expo/vector-icons";

const Tab = createBottomTabNavigator();

const MainTabNavigator = () => {
return (
    <Tab.Navigator
      initialRouteName="Chats"
      screenOptions={{
        tabBarStyle: { backgroundColor: "whitesmoke" },
        headerStyle: { backgroundColor: "whitesmoke" },
      }}
    >
    <Tab.Screen
        name="Chats"
        component={ChatsScreen}
        options={({ navigation }) => ({
          tabBarIcon: ({ color, size }) => (
            <MaterialCommunityIcons
              name="message-processing-outline"
              size={size}
              color={color}
            />
          ),
          headerRight: () => (
            <Entypo
              onPress={() => navigation.navigate("Contacts")}
              name="new-message"
              size={18}
              color={"royalblue"}
              style={{ marginRight: 15 }}
            />
          ),
        })}
      />
    </Tab.Navigator>
);
};

export default MainTabNavigator;

You can do it as below, with a Conditional (ternary) operator .您可以使用Conditional (ternary) operator执行以下操作。 Just replace boleanVariable with your actual variable.只需将boleanVariable替换为您的实际变量即可。

options={({ navigation }) => ({
  tabBarIcon: ({ color, size }) => (
    <MaterialCommunityIcons name="message-processing-outline" size={size} color={color} />
  ),
  headerRight: () =>
    !boleanVariable ? (
      <></>
    ) : (
      <Entypo
        onPress={() => navigation.navigate("Contacts")}
        name="new-message"
        size={18}
        color={"royalblue"}
        style={{ marginRight: 15 }}
      />
    ),
})}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM