[英]How to properly use if statements in React Navigation Native?
我正在构建一个应用程序,用户可以在其中查看不同语言的信息。 用户还可以选择显示信息的语言。 但是,当我尝试为导航栏设置语言时遇到问题。 我正在使用 React Navigation Native 创建导航栏并使用 useContext 挂钩从另一个组件获取所选语言。 如果我在 Navigator 中使用 if 语句,我会得到一个错误:
错误:找不到导航器的任何屏幕。 您是否将任何屏幕定义为其子屏幕?
根据我的理解,mount 上的应用程序没有变量“locale”,也没有任何可显示的内容。 我怎样才能避免这种情况(我应该在某处使用 async function 吗?)?
这是我的代码:
App.js代码
function App() {
const [locale, setLocale] = useState("en");
return (
<LanguageContext.Provider value={{ locale, setLocale }}>
<MainContainer />
</LanguageContext.Provider>
);
}
LanguageContext.js
import { createContext } from "react";
export const LanguageContext = createContext("");
主容器.js
const profileName = "Profile";
const detailsName = "Details";
const settingsName = "Settings";
const profileNameFR = "P";
const detailsNameFR = "D";
const settingsNameFR = "S";
const Tab = createBottomTabNavigator();
export default function MainContainer() {
const { locale } = useContext(LanguageContext);
return (
<NavigationContainer>
<Tab.Navigator
screenOptions={({ route }) => ({
tabBarIcon: ({ focused, color, size }) => {
let iconName;
let rn = route.name;
if (rn === profileName || rn === profileNameFR) {
iconName = focused ? "person" : "person-outline";
} else if (rn === detailsName || rn === detailsNameFR) {
iconName = focused ? "list" : "list-outline";
} else if (rn === settingsName || settingsNameFR) {
iconName = focused ? "settings" : "settings-outline";
}
return <Ionicons name={iconName} size={size} color={color} />;
},
tabBarActiveTintColor: "tomato",
inactiveTintColor: "grey",
tabBarStyle: { padding: 10, height: 60 },
tabBarLabelStyle: { paddingBottom: 10, fontSize: 10 },
style: { padding: 10 },
})}
>
{locale === "en" && (
<>
<Tab.Screen name={profileName} component={ProfileScreen} />
<Tab.Screen name={detailsName} component={DetailsScreen} />
<Tab.Screen name={settingsName} component={SettingsScreen} />
</>
)}
{locale === "fr" && (
<>
<Tab.Screen name={profileNameFR} component={ProfileScreen} />
<Tab.Screen name={detailsNameFR} component={DetailsScreen} />
<Tab.Screen name={settingsNameFR} component={SettingsScreen} />
</>
)}
</Tab.Navigator>
</NavigationContainer>
);
}
我完全忘记了我用来在主要组件中设置语言的 useState。 一开始是
const [locale, setLocale] = useState("");
这意味着当应用程序呈现语言环境变量的值时,它是空字符串。 我需要做的就是将 state 设置为默认应用程序的语言,在我的例子中是“en”,然后应用程序就会运行。
此外,我保留了主要组件,以防万一有人想知道我在这种情况下如何使用 useContext:
App.js代码
function App() {
const [locale, setLocale] = useState("en");
return (
<LanguageContext.Provider value={{ locale, setLocale }}>
<MainContainer />
</LanguageContext.Provider>
);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.