如何为包装组件构建 React 元素树?

问题描述 投票:0回答:1

考虑我有一个下面的应用程序结构

const App = () => {
    return <div><Header /><Main/><Footer/></div>
}
const Header = () => {
    return <>Header</>;
}
const Main= () => {
    return <>Main</>;
}
const Footer= () => {
    return <>Footer</>;
}

使用App组件

<App><div>A</div><App/>

当在反应中遇到上面的行时,它应该创建看起来像这样的元素

{
  $$typeof: Symbol(react.element),
  type: ƒ App(),
  key: null,
  ref: null,
  props: {
    children: {
      $$typeof: Symbol(react.element),
      type: "div",
      key: null,
      ref: null,
      props: {
        children: "A"
      },
      ...
    }
  },
  ...
}

我现在的问题是,当 React 调用 App 组件并继续为 App 组件子组件创建元素时。它们是如何在这棵树中创建的?

进一步,如果我们在 App 组件中使用 props.children ,它是在何时何地在元素树中创建的?

我没有尝试任何东西,我不知道最终的树应该是什么样子。

javascript reactjs babeljs createelement virtual-dom
1个回答
0
投票
  • 当您将子项传递给组件时,它们在
    props.children
    属性中可用。
  • 要渲染这些子项,您需要在组件返回的 JSX 中包含
    props.children
  • 最终的元素树将在组件 JSX 中放置
    props.children
    的位置合并这些子元素。

通过在

props.children
组件的 return 语句中包含
App
,您可以确保传递给 App 的任何子级都将在元素树中正确呈现。

© www.soinside.com 2019 - 2024. All rights reserved.