React如何在单个组合组件中动态传入并渲染不同子组件
完全可以实现,不需要写重复结构的组合组件,两种常用实现方式如下:
方案1:通过props直接接收图标组件(灵活度最高)
React 支持将组件本身作为属性传递,你只需要给组合组件新增一个接收图标组件的prop,直接渲染传入的组件即可,还可以统一透传图标需要的尺寸等配置。
修正后的组件代码:
// src/components/Pet/Pet.tsx import React from "react"; import { CatIcon, DogIcon, PetName } from "~/components"; import type { Size } from "~/components/Icon/type"; // 替换为你项目中Size类型的实际引入路径 export type PetFieldProps = { text: string; // 接收符合图标类型约定的组件 Icon: React.ComponentType<Size>; // 统一透传给图标的尺寸属性 size?: Size; }; export const PetField: React.FC<PetFieldProps> = ({ text, Icon, size }) => { return ( <> <Icon size={size} /> <PetName text={text} /> </> ); };
使用示例:
// 渲染猫图标+名称 <PetField text="橘猫" Icon={CatIcon} size={24} /> // 渲染狗图标+名称 <PetField text="柯基" Icon={DogIcon} size={24} />
注意:你原来的示例代码里PetName组件没有传入必填的text属性,实际运行会报错,上述代码已经修正这个问题。
方案2:内置宠物类型映射(使用更简洁)
如果不想每次调用都手动传入图标组件,可以内置一个类型和图标的映射关系,只需要传宠物类型标识就能自动匹配对应图标,后续新增宠物图标只需要更新映射表即可:
// src/components/Pet/Pet.tsx import React from "react"; import { CatIcon, DogIcon, PetName } from "~/components"; import type { Size } from "~/components/Icon/type"; // 替换为你项目中Size类型的实际引入路径 // 支持的宠物类型枚举 export type PetType = 'cat' | 'dog'; // 宠物类型-对应图标映射表 const PetIconMap: Record<PetType, React.ComponentType<Size>> = { cat: CatIcon, dog: DogIcon } export type PetFieldProps = { text: string; petType: PetType; size?: Size; }; export const PetField: React.FC<PetFieldProps> = ({ text, petType, size }) => { const CurrentIcon = PetIconMap[petType]; return ( <> <CurrentIcon size={size} /> <PetName text={text} /> </> ); };
使用示例:
// 渲染猫图标+名称 <PetField text="橘猫" petType="cat" size={24} /> // 渲染狗图标+名称 <PetField text="柯基" petType="dog" size={24} />
两种方案都能完全避免重复编写结构相同的组合组件,后续如果要加兔子、仓鼠等其他宠物图标,不管是直接传组件还是更新映射表,都不需要改动PetField的核心布局结构。
内容的提问来源于stack exchange,提问作者Alpin Cleopatra
相关产品推荐
相关产品推荐

