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

React将组件作为Prop传递时使用cloneElement报错如何解决

问题原因及解决方案

错误1:cloneElement参数类型不匹配报错

Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined

React.cloneElement的第一个入参要求是已经实例化的React元素(即<Component />格式的产物),你最初的componentsToUse中存储的是组件类/函数本身,不是实例化后的元素,传入cloneElement不符合参数类型要求,因此触发报错。

错误2:提前实例化触发propType校验报错

你直接在componentsToUse中写入<Component />时,代码执行到这里就会立即完成组件实例化,此时还没有传入必填props,因此直接触发propType校验失败。


正确实现方案

推荐直接从映射对象中取出组件构造,再用JSX语法传入对应props渲染即可,不需要用到cloneElement:

// 组件映射保持存储组件构造即可
const componentsToUse = {
  "Key": Component,
  "Key2": Component2,
}

// 渲染逻辑修改为
{array.map((obj) => {
  // 取出对应组件,变量名必须首字母大写才能被JSX识别为自定义组件
  const RenderComp = componentsToUse[obj.key];
  // 加兜底逻辑,避免key不存在导致渲染undefined报错
  if (!RenderComp) return null;
  // 直接渲染组件并传入props,记得加列表渲染的唯一key
  return <RenderComp {...obj.props} key={obj.key} />
})}

可选方案(仅当必须使用cloneElement时)

如果业务场景必须使用cloneElement,可以在渲染时先实例化组件再传入clone,效果和上述方案一致:

{array.map((obj) => {
  const RenderComp = componentsToUse[obj.key];
  if (!RenderComp) return null;
  return React.cloneElement(<RenderComp />, obj.props)
})}

该方案本质和第一种没有性能差异,只是写法更繁琐,无特殊需求优先使用第一种方案。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 04:24:02