首页 > 解决方案 > 使用来自 @react-navigation/native 的 StackScreen 选项

问题描述

我需要在屏幕右侧标题上设置一个按钮。

import { useNavigation } from '@react-navigation/native';

const App = () => {                                                                                                                                                                                                                                                            
  const navigation = useNavigation()
  return (
    <NavigationContainer>
      <Stack.Navigator>
        <Stack.Screen name="Home" component={HomeScreen} options={{headerShown: false}} />
        <Stack.Screen name="Next" component={NextScreen} options={{
          headerRight: () => <Button title="Done" onPress={() => navigation.navigate('Home')}/>,
          headerLeft:null
        }} />
        <Stack.Screen name="SelectPatient" component={SelectPatientScreen} />
      </Stack.Navigator>
    </NavigationContainer>
  )
}

错误消息显示找不到导航对象。您的组件是否在导航器的屏幕内?

我还在 HomeScreen 中使用导航,它可以工作。App.js 中出现错误。我怎样才能将导航对象放在Press 上。谢谢。

标签: react-nativeexporeact-navigation

解决方案


只是Guruparan答案的补充,你不能const navigation = useNavigation()在导航器之外做


推荐阅读