如何将LucideIcon传入React组件?解决类型不兼容报错
解决Next.js中传递Lucide图标时的类型错误
问题根源
你遇到的类型错误是因为KayakDesc组件的image属性被定义为string类型,但实际传入的是lucide-react的图标组件(LucideIcon类型),类型不匹配导致报错。
解决步骤
1. 修改KayakDesc组件的Props类型并正确渲染图标
在kayakdescription.tsx中,导入LucideIcon类型,将image的类型从string改为LucideIcon,并把图标当作React组件渲染:
import Link from "next/link" import type { LucideIcon } from "lucide-react" const KayakDesc = ({ image: Icon, title, subinfo, }: { image: LucideIcon title: string subinfo: string }) => { return ( <div className="flex border rounded-xl w-72 h-40 mx-2 dark:border-gray-400"> <div className="flex p-4"> {/* 将图标作为React组件渲染,可添加类名控制尺寸 */} <Icon className="w-6 h-6" /> <div className="flex-col ml-4"> <div className="font-bold text-lg">{title}</div> <div className="text-xs mt-4">{subinfo}</div> </div> </div> </div> ) } export default KayakDesc
2. 保持图标数据的正确传递
kayaktitleinfo.ts中的写法无需修改,继续传递图标组件即可:
import { BedDouble } from "lucide-react" export const Kayaktitleinfo = [ { title: "Search for the best hotel deals", subinfo: "Compare deals from 3M+ hotels and accommodations in one place.", image: BedDouble, }, ]
3. 可选:为图标数据添加类型定义(增强类型安全)
如果需要更严格的类型校验,可以给Kayaktitleinfo数组定义类型:
import { BedDouble, LucideIcon } from "lucide-react" type KayakInfo = { title: string subinfo: string image: LucideIcon } export const Kayaktitleinfo: KayakInfo[] = [ { title: "Search for the best hotel deals", subinfo: "Compare deals from 3M+ hotels and accommodations in one place.", image: BedDouble, }, ]
内容的提问来源于stack exchange,提问作者Ryomen
相关产品推荐
相关产品推荐

