React:指定嵌套子组件的位置?

React: Specify Location of Nested Children Components?

我想如何设置我的组件层次结构,如下所示:

<Page>
  <Page.Section>
     <Page.Item/>
  </Page.Section>
</Page>
  1. 如何引用子组件的嵌套子组件(又名 Page.Item)以将其放在不同的位置,因为我不希望特定的样式影响它?请参阅代码注释。由于样式原因,我不想更改它。

  2. 如何只允许 Page.SectionPage.ItemPage 组件中使用而不是独立使用?

Page.js

const Page = ({ children }) => {
  return (
    <>
      <div
        className='bg-gray-100 border-b-2 flex flex-col top-0 fixed w-screen transition-height duration-300 mt-16'
      >
        <SomeComponent/>
        // Section Children I want here so it takes styling
        {children}
      </div>
        // Item Children I want here so it does not take styling, but I want the Item Children to always be nested in The Page.Section Component.
        {children.children?}
    </>
  );
};

// I want his Section element to be
const Section = ({ children }) => {
  return (
    <>
      <ConfiguratorTab/>
      {children}
    </>
  );
};

const Item = () => {
  return (
    <>
      <Form/>
    </>
  );
};

Page.Section = Section;
Page.Item = Item;

export default Page;

children returns 具有以下键和值的对象。

type: ƒ Section() {}
key: null
ref: null
props: Object
_owner: FiberNode
_store: Object

props 对象保存传递给当前(父)组件的 prop 值。因此可以使用 props 访问子组件的子组件。由于 ItemPage 的子项(尽管不是直接子项),如果您不想应用某些样式,则无需将其再次包含在 Section 组件中给它。这可以通过从 Section.

中删除 children 来实现
const Section = ({ children }) => {
  return (
    <>
      <ConfiguratorTab/>
      {//Don't render any children elements here.
      }
    </>
  );
};
const Page = ({ children }) => {
  return (
    <>
      <div
        className='bg-gray-100 border-b-2 flex flex-col top-0 fixed w-screen transition-height duration-300 mt-16'
      >
        <SomeComponent/>
        // Section Children I want here so it takes styling
        {children}
      </div>
        // Item Children I want here so it does not take styling, but I want the Item Children to always be nested in The Page.Section Component.
        {children.props.children}
    </>
  );
};