react-navigation中Screen定义及stateless组件导航适配咨询
Hey there! Let's tackle your React Navigation questions one by one:
1. What counts as a "Screen" component in React Navigation?
Yep! Any component you define in the RouteConfigs of a navigator (like StackNavigator) is treated as a Screen. As long as it's registered in your navigation stack/tab setup, it becomes part of the navigation hierarchy and qualifies as a Screen.
2. Does a Screen have to be an ES6 Class component?
Absolutely not! Functional components (including stateless functional components) work perfectly fine as Screens. The issue you ran into with this.props.navigation being undefined wasn't because of the component type—it's because you weren't accessing the props correctly in your functional component.
3. How to make stateless functional components work with navigation?
There are two straightforward ways to get access to the navigation props in a functional component:
Explicitly accept props as an argument
Functional components receive props directly, so you just need to include them in your component definition:const MyFunctionalScreen = (props) => { return ( <View> <Button title="Go to Next Screen" onPress={() => props.navigation.navigate('NextScreen')} /> </View> ); };Note: Functional components don't have a
thiskeyword, so usingthis.propshere would never work—you have to use thepropsparameter directly.Use the
useNavigationHook (React Navigation 5+)
If you're using React Navigation 5 or later, Hooks are the recommended approach. You can import and useuseNavigationto get the navigation object without relying on props:import { useNavigation } from '@react-navigation/native'; const MyFunctionalScreen = () => { const navigation = useNavigation(); return ( <View> <Button title="Go to Next Screen" onPress={() => navigation.navigate('NextScreen')} /> </View> ); };
To recap: Both class and functional components are valid as Screens, as long as they're registered in your navigator's config. The key issue you faced was forgetting to accept props in your functional component (or not using the Hook), not the component type itself.
内容的提问来源于stack exchange,提问作者Andreas Andreou

