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

React+TypeScript中Headless UI Tab组件selected属性类型问题

问题解决:Headless UI Tab组件className回调TypeScript类型错误

核心问题

你的代码里className的回调函数没有返回值——你用大括号包裹了函数体,但没写return语句,导致TypeScript判定这个函数返回void,而Headless UI要求className回调必须返回字符串类型。

修正后的代码

把classNames的调用结果返回即可:

<Tab
    className={({ selected }) => {
        // 加上return,返回classNames生成的字符串
        return classNames(
            "w-full rounded-lg py-2.5 text-sm font-medium leading-5 text-blue-700",
            "ring-white ring-opacity-60 ring-offset-2 ring-offset-blue-400 focus:outline-none focus:ring-2",
            selected ? "bg-blue-50" : "bg-blue-100"
        );
    }}
></Tab>

或者简化成箭头函数的隐式返回(去掉大括号):

<Tab
    className={({ selected }) => classNames(
        "w-full rounded-lg py-2.5 text-sm font-medium leading-5 text-blue-700",
        "ring-white ring-opacity-60 ring-offset-2 ring-offset-blue-400 focus:outline-none focus:ring-2",
        selected ? "bg-blue-50" : "bg-blue-100"
    )}
></Tab>

如何查询selected的类型

  • IDE直接跳转:在VSCode等IDE里,按住Ctrl(Mac为Cmd)点击selected参数,就能跳转到Headless UI的类型定义文件,查看它的具体类型(实际为boolean)。
  • 查看组件Props类型:找到Tab组件的className属性类型,它是一个接收TabRenderPropArg参数的函数,这个类型里明确包含selected: boolean的定义。

内容的提问来源于stack exchange,提问作者liam

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 03:42:08