在 React 中克隆功能元件
P粉851401475
P粉851401475 2023-09-10 17:44:34
0
1
301

我試圖修改和複製我正在建立的元件的子元素,最近注意到我的 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() 是克隆整個子元素樹的唯一方法嗎?

P粉851401475
P粉851401475

熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!