useNavigation
useNavigation
是一个可以访问 navigation
对象的钩子。当你无法将 navigation
对象作为 prop 直接传递给组件,或者不想在子组件嵌套较深的情况下传递它时,它很有用。
¥useNavigation
is a hook that gives access to navigation
object. It's useful when you cannot pass the navigation
object as a prop to the component directly, or don't want to pass it in case of a deeply nested child.
useNavigation
钩子返回使用它的屏幕的 navigation
对象:
¥The useNavigation
hook returns the navigation
object of the screen where it's used:
- Static
- Dynamic
import { useNavigation } from '@react-navigation/native';
function MyBackButton() {
const navigation = useNavigation();
return (
<Button
onPress={() => {
navigation.goBack();
}}
>
Back
</Button>
);
}
import { useNavigation } from '@react-navigation/native';
function MyBackButton() {
const navigation = useNavigation();
return (
<Button
onPress={() => {
navigation.goBack();
}}
>
Back
</Button>
);
}
检查如何使用 TypeScript 此处 设置 useNavigation
。
¥Check how to setup useNavigation
with TypeScript here.
有关详细信息,请参阅 navigation
对象 的文档。
¥See the documentation for the navigation
object for more info.
与类组件一起使用
¥Using with class component
你可以将类组件封装在函数组件中以使用钩子:
¥You can wrap your class component in a function component to use the hook:
class MyBackButton extends React.Component {
render() {
// Get it from props
const { navigation } = this.props;
}
}
// Wrap and export
export default function (props) {
const navigation = useNavigation();
return <MyBackButton {...props} navigation={navigation} />;
}