Skip to main content
Version: 6.x

useLinkBuilder

useLinkBuilder 钩子允许我们构建一条路径,用于当前导航器状态下屏幕的链接。它返回一个函数,该函数采用 nameparams 作为屏幕焦点,并返回基于 linking 选项 的路径。

¥The useLinkBuilder hook 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 { Link, CommonActions, useLinkBuilder } from '@react-navigation/native';

// ...

function DrawerContent({ state, descriptors }) {
const buildLink = useLinkBuilder();

return state.routes((route) => (
<Link
to={buildLink(route.name, route.params)}
action={CommonActions.navigate(route.name)}
>
{descriptors[route.key].options.title}
</Link>
));
}

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

¥This hook is intended to be used in navigators to show links to various pages in it, 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.

  • 它仅用于自定义导航器,以使其可在多个应用中重复使用。对于常规应用代码,直接使用路径而不是为屏幕构建路径,或者使用 LinkuseLinkProps 来透明地处理路径。

    ¥It's intended to be only used in custom navigators to keep them reusable in multiple apps. For your regular app code, use paths directly instead of building paths for screens, or use Link and useLinkProps which transparently handle paths.