我正在尝试实现React.createElement()。但我得到了以下错误
未捕获的错误:对象作为React子对象无效(找到:具有键{type,props}的对象)。如果要渲染子对象的集合,请改用数组。
但当我尝试原始函数{React.createElement}时,我的是{Reacto.createElement},它可以工作
但如果我记录Original和我的函数返回的元素,它们几乎是一样的
这是代码
import {createRoot} from "react-dom/client";
import React from "react";
function createTextElement(text){
return text
}
function createElement( type , props , ...children ){
return{
type,
props : {
...props,
children : children.map(child =>
typeof child === "object"
? child
: createTextElement(child)
),
},
}
}
const Reacto = {
createElement,
}
const element = Reacto.createElement(
'h1',
{ className: 'greeting' },
"This is another",
'Hello'
);
const elementReact = React.createElement(
'h1',
{ className: 'greeting' },
'Hello',
"This is another"
);
console.log(element);
console.log(elementReact);
const root = createRoot(document.getElementById("root"));
root.render(element)
这是一些日志
这是我的元素
Object { type: "h1", props: {â¦} }
â
props: Object { className: "greeting", children: (2) [â¦] }
ââ
children: Array [ "This is another", "Hello" ]
âââ
0: "This is another"
âââ
1: "Hello"
âââ
length: 2
âââ
<prototype>: Array []
ââ
className: "greeting"
ââ
<prototype>: Object { ⦠}
â
type: "h1"
â
<prototype>: Object { ⦠}
这是Reacts元素
Object { "$$typeof": Symbol("react.element"), type: "h1", key: null, ref: null, props: {â¦}, _owner: null, _store: {â¦}, ⦠}
â
"$$typeof": Symbol("react.element")
â
_owner: null
â
_self: null
â
_source: null
â
_store: Object { ⦠}
â
key: null
â
props: Object { className: "greeting", children: (2) [â¦] }
ââ
children: Array [ "Hello", "This is another" ]
âââ
0: "Hello"
âââ
1: "This is another"
âââ
length: 2
âââ
<prototype>: Array []
ââ
className: "greeting"
ââ
<prototype>: Object { ⦠}
â
ref: null
â
type: "h1"
我不知道发生了什么事,如果你知道的话,任何事情都会有所帮助。