You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.01 22:03:12