我试图修改和克隆我正在创建的组件的子元素,最近注意到我的 children 类型根据我传递 children 的方式而发生变化>.
例如,如果我将 JSX 作为孩子传递:
<MyComponent> <div>Hello</div> </MyComponent>
当我检查 MyComponent 中的 children 结构时,我可以看到该对象如下:
{
'$$typeof': Symbol(react.element),
type: 'div',
key: null,
ref: null,
props: { children: 'hello' },
_owner: null,
_store: {}
}
由于 props.children 存在,所以 React.cloneElement 可以直接使用它。
如果我创建一个像这样的功能组件:
const Hello: React.FC = () => <div>hello</div>;
并尝试像这样使用它:
<MyComponent> <Hello/> </MyComponent>
那么children对象的结构就变成了这样:
{
'$$typeof': Symbol(react.element),
type: [Function: Hello],
key: null,
ref: null,
props: {},
_owner: null,
_store: {}
}
我不能再使用React.cloneElement,除非我调用children.type(),但我找不到太多相关文档。
为什么会发生这种情况?这是预期的吗?调用 children.type() 是克隆整个子元素树的唯一方法吗?
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
Hello 是一个 div,是一个返回 div 的函数,所以显然它们不是同一件事。有一个空对象作为props,因为它没有子对象,而且我们没有向它传递一个带有值的属性,因此props是{}。您真正想要访问和克隆的是
返回的父 JSX 元素的子元素,这与其 props 无关。返回的父 JSX 元素实际上是
children.type()(函数返回的内容)该元素将 childs 包裹在其中(Hello),因此children.type().props.children 也存在于此,因此您可以克隆它。