[英]React: Specify Location of Nested Children Components?
我想如何設置我的組件層次結構是這樣設置的:
<Page>
<Page.Section>
<Page.Item/>
</Page.Section>
</Page>
我如何引用子組件(又名Page.Item
)的嵌套子組件以放置在不同的位置,因為我不希望特定樣式影響它? 請參閱代碼注釋。 由於樣式,我不想更改它。
如何只允許Page.Section
和Page.Item
在Page
組件中使用而不是獨立使用?
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
訪問子組件的子組件。 由於Item
是Page
的子項(盡管不是直接子項),如果您不想將某些 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.