Skip to main content
Version: 6.x

useRoute

useRoute 是一个钩子,可以访问 route 对象。当你无法将 route 属性直接传递到组件中,或者不想在深度嵌套子组件的情况下传递它时,它非常有用。

¥useRoute is a hook which gives access to route object. It's useful when you cannot pass the route prop into the component directly, or don't want to pass it in case of a deeply nested child.

useRoute() 返回其内部屏幕的 route 属性。

¥useRoute() returns the route prop of the screen it's inside.

示例

¥Example

import * as React from 'react';
import { Text } from 'react-native';
import { useRoute } from '@react-navigation/native';

function MyText() {
const route = useRoute();

return <Text>{route.params.caption}</Text>;
}

有关详细信息,请参阅 route 属性 的文档。

¥See the documentation for the route prop for more info.

与类组件一起使用

¥Using with class component

你可以将类组件封装在函数组件中以使用钩子:

¥You can wrap your class component in a function component to use the hook:

class MyText extends React.Component {
render() {
// Get it from props
const { route } = this.props;
}
}

// Wrap and export
export default function (props) {
const route = useRoute();

return <MyText {...props} route={route} />;
}