useLinkProps
useLinkProps
Hook 让我们构建自定义链接组件。链接组件可以用作导航到屏幕的按钮。在 Web 上,它将渲染为带有 href
属性的锚标记 (<a>
),以便保留链接的所有辅助功能,例如 - 诸如 右键单击 -> 在新标签页中打开链接
、Ctrl+单击
/⌘+单击
等。
它返回一个对象,其中包含一些你可以传递给组件的 props。
示例
import { useLinkProps } from '@react-navigation/native';
// ...
const LinkButton = ({ screen, params, action, href, children, ...rest }) => {
const props = useLinkProps({ screen, params, action, href });
const [isHovered, setIsHovered] = React.useState(false);
return (
<Pressable {...props} {...rest}>
<Text>{children}</Text>
</Pressable>
);
};
然后你可以在你的应用程序的其他地方使用 LinkButton
组件
function Home() {
return (
<LinkButton screen="Profile" params={{ id: 'jane' }}>
Go to Jane's profile
</LinkButton>
);
}
选项
screen
和 params
你可以传递 screen
和 params
以在按下时导航到屏幕
function Home() {
return (
<LinkButton screen="Profile" params={{ id: 'jane' }}>
Go to Jane's profile
</LinkButton>
);
}
如果你想导航到嵌套屏幕,你可以将 screen
的名称传递到 params
中,类似于导航到嵌套导航器中的屏幕
<LinkButton screen="Root" params={{ screen: 'Post', params: { id: 123 } }}>
Go to post 123
</LinkButton>
action
有时我们希望页面内导航具有不同的行为,例如 replace
而不是 navigate
。我们可以使用 action
prop 来自定义它
示例
import { StackActions } from '@react-navigation/native';
// ...
function Home() {
return (
<LinkButton
screen="Profile"
params={{ id: 'jane' }}
action={StackActions.replace('Profile', { id: 'jane' })}
>
Go to Jane's profile
</LinkButton>
);
}
如果指定了 action
prop,则可以省略 screen
和 params
props。 在这种情况下,我们建议也指定 href
prop,以确保链接是可访问的。
href
href
用于 Web 上锚标记的 href
属性,以使链接可访问。 默认情况下,这是根据 linking
选项 使用 screen
和 params
props 自动确定的。
如果你想使用自定义 href
,你可以将其作为 href
prop 传递
function Home() {
return (
<LinkButton
action={StackActions.replace('Profile', { id: 'jane' })}
href="/users/jane"
>
Getting Started
</LinkButton>
);
}