【问题标题】:React Navigation v5: How to write a navigation route for a custom Navigation header button?React Navigation v5:如何为自定义导航标题按钮编写导航路线?
【发布时间】:2021-07-27 16:42:42
【问题描述】:

我正在尝试在我的应用程序的所有屏幕的导航标题的headerRight 上添加一个“齿轮”按钮。我在App.js 中的NavigationContainer 中添加了ScreenOptionsStack.Navigator 按钮,以便此堆栈中的所有Stack.Screens 在标题上都有此按钮。

现在我需要按下这个按钮来导航到另一个屏幕(settingsScreen)。我无法像在屏幕上那样将navigation.navigate('settingsScreen') 添加到按钮的 onPress 事件中,因为 App.js 文件中没有可用的导航道具。这是我的代码 sn-p。

const Stack = createStackNavigator();

const myStack = () => {
  return (
    <NavigationContainer>
      <Stack.Navigator
        screenOptions={{
          headerRight: () => (
            <Button
              title='Gears'
              onPress={() => {}}   // no navigation prop available on this file
            />
          ),
        }}
      >
        <Stack.Screen
          name='Home'
          component={HomeScreen}
          options={{ title: 'Home' }}
        />
        <Stack.Screen
          name='Add new expense'
          component={AddNewExpense}
        />
        <Stack.Screen
          name='Settings'
          component={SettingsScreen}
        />
      </Stack.Navigator>
    </NavigationContainer>
  );
}

如何做到这一点?提前致谢!

【问题讨论】:

  • 我尝试将 Stack 放在“SuperStack”中,并将整个 Stack.Navigator 作为 SuperStack.Screen 的组件传递,这样我就可以使用 navigation.navigate() 作为“Gear”按钮onPress,它可以工作(现在有嵌套的标题),但感觉就像在作弊。有没有更多的反应导航方式来做到这一点?

标签: reactjs react-native react-navigation


【解决方案1】:

screenOptions 将接收每个屏幕的导航道具和路线道具,请参阅here

screenOptions={({ navigation}) => ({
   //you can use navigation now
   headerRight: () => (
     <Button
     title='Gears'
     onPress={() => navigation.navigate('settingsScreen')} 
     />
   ),

})}

【讨论】:

    猜你喜欢
    • 2021-01-29
    • 1970-01-01
    • 2019-01-30
    • 1970-01-01
    • 2021-12-23
    • 2021-07-31
    • 1970-01-01
    • 2020-12-06
    • 2020-06-12
    相关资源
    最近更新 更多