Skip to main content
Version: 7.x

useLinkBuilder

useLinkBuilder 钩子返回助手以根据链接选项构建 href 或操作。它返回一个具有以下属性的对象:

¥The useLinkBuilder hook returns helpers to build href or action based on the linking options. It returns an object with the following properties:

buildHref

buildHref 方法让我们可以构建一条路径,用于当前导航器状态下的屏幕链接。它返回一个函数,该函数采用 nameparams 作为屏幕焦点,并返回基于 linking 选项 的路径。

¥The buildHref method lets us build a path to use for links for a screen in the current navigator's state. It returns a function that takes name and params for the screen to focus and returns path based on the linking options.

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>
));
}

此钩子旨在用于导航器中,以显示导航器中各个页面的链接,例如抽屉和选项卡导航器。如果你正在构建自定义导航器、自定义抽屉内容、自定义选项卡栏等,那么你可能需要使用此钩子。

¥This hook is intended to be used in navigators to show links to various pages in the navigator, such as drawer and tab navigators. If you're building a custom navigator, custom drawer content, custom tab bar etc. then you might want to use this hook.

有几点需要注意:

¥There are couple of important things to note:

  • 目标屏幕必须存在于当前导航器中。它不能位于父导航器或嵌套在子导航器中。

    ¥The destination screen must be present in the current navigator. It cannot be in a parent navigator or a navigator nested in a child.

  • 它仅用于自定义导航器,以使其可在多个应用中重复使用。对于常规应用代码,请直接使用屏幕名称,而不是为屏幕构建路径。

    ¥It's intended to be only used in custom navigators to keep them reusable in multiple apps. For your regular app code, use screen names directly instead of building paths for screens.

buildAction

buildAction 方法让我们将 href 字符串解析为一个动作对象,该对象可与 navigation.dispatch 一起使用以导航到相关屏幕。

¥The buildAction method lets us parse a href string into an action object that can be used with navigation.dispatch to navigate to the relevant screen.

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 钩子是此钩子的便捷封装器,可使用 href 字符串导航到屏幕。

¥The useLinkTo hook is a convenient wrapper around this hook to navigate to a screen using a href string.