我试图修改和克隆我正在创建的组件的子元素,最近注意到我得到的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()是克隆整个子元素树的唯一方法吗?

推荐答案

<div>Hello</div> is a div, <Hello/> is a function that returns a div so obviously they are not the same thing.
<Hello/> has an empty object as props because it has no children and we didn't pass it an attribute with a value so props is {}.

您真正想要访问和克隆的是由<Hello/>返回的父JSX元素的子元素,这与它的props 无关.
返回的父JSX元素实际上是children.type()(函数返回的内容)该元素中包装了子元素(Hello),因此children.type().props.children也在其中,因此您可以克隆它.

Reactjs相关问答推荐

使用`Link`包装`tr`标记会在Next.js中产生水合错误14

梅X折线图无响应

页面永远加载API/从数据库获取数据

是否为Reaction中未使用的组件生成Tailwincss样式?

状态更改是否卸载功能组件

React 在第一次渲染时为 null

有没有办法在 React Router v6 中的路由匹配上运行一些逻辑/功能?

在reactjs中刷新页面时丢失状态值

显示我是否加入聊天应用程序时出现问题

文本的几个词具有线性渐变 colored颜色 - React native

为什么 setState 在 React 中不是异步的?

Reactjs 表单未反映提交时的更改

使用 react-router-dom 时弹出空白页面

如何使图标适合 react-bootstrap 中的行元素

NextJs - 如何从站点 map 生成器中删除重复的 URL?

如何将 id 从页面传递到另一个页面?

交换键仍然引入了 fresh 的 DOM 元素

如何通过 Material Ui 设计将 Accordion 添加到您的 React 项目中?

试图将页面限制为仅登录但有条件的用户似乎永远不会运行

react 路由:router.ts:11 没有匹配的路由位置/管理