从任何组件访问导航属性
useNavigation
是一个钩子,可以访问 navigation
对象。当你无法将 navigation
属性直接传递到组件中,或者不想在深度嵌套子组件的情况下传递它时,它非常有用。
¥useNavigation
is a hook which gives access to the navigation
object. It's useful when you cannot pass the navigation
prop into the component directly, or don't want to pass it in case of a deeply nested child.
非屏幕组件的普通组件不会自动接收导航属性。例如在此 GoToButton
组件中:
¥An ordinary component that is not a screen component will not receive the navigation prop automatically. For example in this GoToButton
component:
import * as React from 'react';
import { Button } from 'react-native';
function GoToButton({ navigation, screenName }) {
return (
<Button
title={`Go to ${screenName}`}
onPress={() => navigation.navigate(screenName)}
/>
);
}
要解决此异常,你可以在从屏幕渲染时将 navigation
属性传递给 GoToButton
,如下所示:<GoToButton navigation={props.navigation} />
。
¥To resolve this exception, you could pass the navigation
prop in to GoToButton
when you render it from a screen, like so: <GoToButton navigation={props.navigation} />
.
或者,你可以使用 useNavigation
自动提供 navigation
属性(如果你好奇的话,可以通过 React 上下文)。
¥Alternatively, you can use the useNavigation
to provide the navigation
prop automatically (through React context, if you're curious).
¥
import * as React from 'react';
import { Button } from 'react-native';
import { useNavigation } from '@react-navigation/native';
function GoToButton({ screenName }) {
const navigation = useNavigation();
return (
<Button
title={`Go to ${screenName}`}
onPress={() => navigation.navigate(screenName)}
/>
);
}
使用这种方法,你可以在应用中的任何位置渲染 GoToButton
,而无需显式传递 navigation
属性,并且它将按预期工作。
¥Using this approach, you can render GoToButton
anywhere in your app without passing in a navigation
prop explicitly and it will work as expected.