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
相关产品推荐
相关产品推荐

