我试图修改和克隆我正在创建的组件的子元素,最近注意到我得到的children
的类型根据我传递children
的方式而改变.
例如,如果我作为子元素通过了JSX:
<MyComponent>
<div>Hello</div>
</MyComponent>
当我判断MyComponent
中的children
struct 时,我可以看到对象如下所示:
{
'$$typeof': Symbol(react.element),
type: 'div',
key: null,
ref: null,
props: { children: 'hello' },
_owner: null,
_store: {}
}
这可以由React.cloneElement
直接使用,因为存在props.children
.
相反,如果我创建一个功能组件,如下所示:
const Hello: React.FC = () => <div>hello</div>;
试着这样使用它:
<MyComponent>
<Hello/>
</MyComponent>
那么children
对象的 struct 就变成了这样:
{
'$$typeof': Symbol(react.element),
type: [Function: Hello],
key: null,
ref: null,
props: {},
_owner: null,
_store: {}
}
我不能再使用React.cloneElement
,除非我呼叫children.type()
,但我找不到关于children.type()
的太多文档.
为什么会发生这种情况,这是意料之中的吗?拨打children.type()
是克隆整个子元素树的唯一方法吗?