使用React.cloneElement克隆组件报Element type is invalid如何解决?
问题原因
- 你对
React.cloneElement的入参规则理解有误:该API的第一个参数要求是已经实例化的React元素(即通过<Component />语法生成的React元素对象),你传入的是Button组件的定义函数本身,不符合入参要求,返回了无效的元素类型,因此触发报错。 UserButton组件没有接收、透传父级传入的children属性,即便克隆逻辑正确,也无法获取到<UserButton>Alex</UserButton>中传入的"Alex"内容。
解决方案
修正UserButton组件的逻辑,给React.cloneElement传入正确的Button元素实例,同时透传children属性即可,代码如下:
import React from "react"; // 接收children参数 export function UserButton({ children }) { return React.cloneElement(<Button />, { label: "Hello! nice to see you" }, children); }
如果你的场景不需要强制使用React.cloneElement,也可以直接渲染Button组件,写法更简洁:
export function UserButton({ children }) { return <Button label="Hello! nice to see you">{children}</Button> }
修改后即可正常渲染出内容为"Hello! nice to see you Alex"的按钮。
内容的提问来源于stack exchange,提问作者Alexey Tseitlin
相关产品推荐
相关产品推荐

