react-navigation 5.x createBottomTabNavigator 動態修改tabbar的頁面標題


版本:

expo v39.x
react-navigation 5.x
react native hook
Typescript

默認頁面標題是調取 name字段的值

期望是標題分別顯示對應tabbar的標題,如:首頁、關注、熱門

解決方案:

修改 index.tsx 文件

注意,這里不能在BottomTabNavigator.tsx上修改,會造成錯誤 Warning: Cannot update a component from inside the function body of a different component.

正確寫法如下:

//...
function RootNavigator() {
  return (
    <Stack.Navigator>
      <Stack.Screen
        name="Root"
        component={BottomTabNavigator}
        options={({ route }: { route: any }) => {
          const routeName = route.state?.routes[route.state?.index]?.name;
          let title = '首頁';
          if (routeName === 'Home') {
            title = '首頁';
          } else if (routeName === 'Look') {
            title = '關注';
          } else if (routeName === 'Hot') {
            title = '熱門';
          }
          return {
            title: title,
            headerStyle: {
              backgroundColor: Colors.primaryColor,
            },
            headerTintColor: '#fff',
          };
        }}
      />
      // ...
</Stack.Navigator>
)
}

通過 routeName 來手動設置每個頁面的標題


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM