如何通过映射列表向组件传递另一个组件的引用?
解决React组件映射中渲染自定义JSX描述组件的问题
问题背景
我有如下结构的对象数组:
export const serviceList = [ { title: "Exterior Services", image: "/images/service-card-images/kendall-painting.webp", description: "ExteriorServicesDescription", id: 1, link: "/services/painting", }, ];
我需要将该列表映射到ServiceCard组件展示信息,希望description区域渲染包含<p>标签和列表的复杂JSX,因此创建了<ExteriorServicesDescription />组件。
尝试过两种方式但都失败:
- 将
description类型设为React.ReactNode并直接传入<ExteriorServicesDescription />,但lint仅将其识别为类型 - 传入组件名字符串,在映射时尝试
<service.description />,页面仅渲染出<exteriorservicesdescription></exteriorservicesdescription>标签,无实际内容
以下是ServiceCard组件代码:
import React from "react"; import ExteriorServicesDescription from "./ExteriorServicesDescription"; import Image from "next/image"; interface ServiceCardProps { title: string; image: string; description: React.ReactNode; link: string; } const ServiceCard = ({ title, image, description, link }: ServiceCardProps) => { return ( <div className="w-4/5 flex flex-col items-center m-auto justify-center no-underline border-2 rounded-2xl shadow-black shadow border-black"> <div className="w-full h-64 relative"> <Image src={image} alt={title} fill={true} className="rounded-t-xl" /> </div> <h2 className="text-xl no-underline bg-black text-gold w-full text-center py-2"> {title} </h2> {description} <a href={link} className="text-lg border rounded-2xl border-black px-2 py-1 mb-2 hover:bg-slate-300 hover:scale-105 transition-all duration-100" > Learn More </a> </div> ); }; export default ServiceCard;
解决方法
方案一:直接在数组中传入组件实例
修改serviceList,将description字段直接赋值为<ExteriorServicesDescription />组件实例,这样映射时可以直接传递给ServiceCard:
// 先导入对应的描述组件 import ExteriorServicesDescription from "./ExteriorServicesDescription"; export const serviceList = [ { title: "Exterior Services", image: "/images/service-card-images/kendall-painting.webp", description: <ExteriorServicesDescription />, // 直接传入组件实例 id: 1, link: "/services/painting", }, ];
映射代码保持简洁即可:
{serviceList.map((service) => ( <ServiceCard key={service.id} title={service.title} image={service.image} description={service.description} // 直接传递 link={service.link} /> ))}
方案二:创建组件映射表(适合多组件场景)
如果需要管理多个描述组件,可先创建一个组件映射对象,通过字符串匹配获取对应的组件,再渲染:
- 创建组件映射表:
import ExteriorServicesDescription from "./ExteriorServicesDescription"; // 导入其他描述组件 // import InteriorServicesDescription from "./InteriorServicesDescription"; const DescriptionComponents = { ExteriorServicesDescription, // InteriorServicesDescription };
- 修改映射逻辑:
{serviceList.map((service) => { const DescriptionComponent = DescriptionComponents[service.description as keyof typeof DescriptionComponents]; return ( <ServiceCard key={service.id} title={service.title} image={service.image} description={DescriptionComponent ? <DescriptionComponent /> : null} link={service.link} /> ); })}
这种方式适合需要动态匹配多个组件的场景,避免在数组中直接引入大量组件。
注意事项
ServiceCardProps中的description类型保持React.ReactNode即可,它能接收组件实例、JSX元素等多种类型- 方案二中要确保字符串与组件映射表中的键完全一致,否则会找不到组件导致渲染null
内容的提问来源于stack exchange,提问作者Mossy82
相关产品推荐
相关产品推荐

