如何在Qwik中使用动态组件名?动态Link点击无响应问题
问题原因与解决方案
你的代码动态切换Link和<button>时,没把href属性传递给Link组件,这导致Qwik City的Link无法识别跳转目标,点击自然没反应。另外原生<button>不需要href属性,得避免把它传给button。
修正后的代码如下:
import { Slot, component$ } from "@builder.io/qwik"; import { Link } from "@builder.io/qwik-city"; interface ButtonProps { href?: string; } export const Button = component$<ButtonProps>(({ href, ...restProps }) => { const Component = href ? Link : "button"; return ( <Component class="cursor-pointer select-none bg-blue-600 px-4 py-2 text-white" {...(href ? { href } : {})} {...restProps} > <Slot /> </Component> ); });
关键修改点:
- 用
...(href ? { href } : {})条件传递href属性:只有当href存在时,才把它传给Link组件,避免传给原生button。 - 新增
...restProps让组件支持接收其他通用属性(比如onClick、disabled等),提升扩展性。
修改后,传入href时Link会正确获取跳转地址,点击可正常导航;无href时就是普通button组件,功能正常。
内容的提问来源于stack exchange,提问作者Konrad
相关产品推荐
相关产品推荐

