繁体   English   中英

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返回带有以下键和值的 object。

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

props object 保存传递给当前(父)组件的道具值。 因此可以使用props访问子组件的子组件。 由于ItemPage的子项(尽管不是直接子项),如果您不想将某些 styles 应用到它,则无需将其再次包含在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}
    </>
  );
};

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM