虽然在许多情况下重复代码是可以接受的,但您可能会发现自己过于频繁地这样做。有时,您可能希望创建具有额外行为或样式的横切组件。您也可以考虑将第三方库与 TanStack Router 的类型安全功能结合使用。
createLink 创建一个与 Link 具有相同类型参数的自定义 Link 组件。这意味着您可以创建自己的组件,提供与 Link 相同的类型安全和 TypeScript 性能。
如果您想创建一个基础的自定义链接组件,可以按照以下方式实现:
import * as Solid from 'solid-js'
import { createLink, LinkComponent } from '@tanstack/solid-router'
export const Route = createRootRoute({
component: RootComponent,
})
type BasicLinkProps = Solid.JSX.IntrinsicElements['a'] & {
// Add any additional props you want to pass to the anchor element
}
const BasicLinkComponent: Solid.Component<BasicLinkProps> = (props) => (
<a {...props} class="block px-3 py-2 text-red-700">
{props.children}
</a>
)
const CreatedLinkComponent = createLink(BasicLinkComponent)
export const CustomLink: LinkComponent<typeof BasicLinkComponent> = (props) => {
return <CreatedLinkComponent preload={'intent'} {...props} />
}
import * as Solid from 'solid-js'
import { createLink, LinkComponent } from '@tanstack/solid-router'
export const Route = createRootRoute({
component: RootComponent,
})
type BasicLinkProps = Solid.JSX.IntrinsicElements['a'] & {
// Add any additional props you want to pass to the anchor element
}
const BasicLinkComponent: Solid.Component<BasicLinkProps> = (props) => (
<a {...props} class="block px-3 py-2 text-red-700">
{props.children}
</a>
)
const CreatedLinkComponent = createLink(BasicLinkComponent)
export const CustomLink: LinkComponent<typeof BasicLinkComponent> = (props) => {
return <CreatedLinkComponent preload={'intent'} {...props} />
}
然后,您可以像使用其他 Link 组件一样使用新创建的 Link 组件:
<CustomLink to={'/dashboard/invoices/$invoiceId'} params={{ invoiceId: 0 }} />
<CustomLink to={'/dashboard/invoices/$invoiceId'} params={{ invoiceId: 0 }} />
Here are some examples of how you can use createLink with third-party libraries.
// TODO: Add this example.
// TODO: Add this example.
注意:所有代码块、URL、文件路径和变量名称均保持原样未翻译。
Your weekly dose of JavaScript news. Delivered every Monday to over 100,000 devs, for free.