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 来手动设置每个页面的标题

posted @ 2020-10-20 16:30  Function-Fun  阅读(1099)  评论(0)    收藏  举报