useLinkBuilder
useLinkBuilder
Hook 返回辅助函数,用于基于链接选项构建 href
或 action。它返回一个具有以下属性的对象
buildHref
buildHref
方法允许我们构建一个路径,用于当前导航器状态中屏幕的链接。它返回一个函数,该函数接受要聚焦的屏幕的 name
和 params
,并基于 linking
选项返回路径。
import { useLinkBuilder } from '@react-navigation/native';
import { PlatformPressable } from '@react-navigation/elements';
// ...
function DrawerContent({ state, descriptors, navigation }) {
const { buildHref } = useLinkBuilder();
return state.routes((route) => (
<PlatformPressable
href={buildHref(route.name, route.params)}
onPress={() => navigation.navigate(route.name, route.params)}
>
{descriptors[route.key].options.title}
</PlatformPressable>
));
}
此 Hook 旨在用于导航器中,以显示导航器中各个页面的链接,例如抽屉和标签导航器。如果您正在构建自定义导航器、自定义抽屉内容、自定义标签栏等,那么您可能需要使用此 Hook。
有几点重要注意事项:
- 目标屏幕必须存在于当前导航器中。它不能位于父导航器或子导航器中嵌套的导航器中。
- 它仅旨在用于自定义导航器,以使其在多个应用中可重用。对于您的常规应用代码,请直接使用屏幕名称,而不是为屏幕构建路径。
buildAction
buildAction
方法允许我们将 href
字符串解析为 action 对象,该对象可以与 navigation.dispatch
一起使用以导航到相关屏幕。
import { Link, CommonActions, useLinkBuilder } from '@react-navigation/native';
import { Button } from '@react-navigation/elements';
// ...
function MyComponent() {
const { buildAction } = useLinkBuilder();
return (
<Button onPress={() => navigation.dispatch(buildAction('/users/jane'))}>
Go to Jane's profile
</Button>
);
}
useLinkTo
Hook 是此 Hook 的便捷包装器,用于使用 href
字符串导航到屏幕。