gpt4 book ai didi

reactjs - 渲染 React 嵌套组件

转载 作者:行者123 更新时间:2023-12-05 08:09:09 27 4
gpt4 key购买 nike

有没有办法在不同的 div 下渲染 React 组件的子组件?

<Page>
<Header> ... </Header>
<Content> ... </Content>
<Actions> ... </Actions>
</Page>

<div class="page">
<div class="header-wrapper>
<div class="header"> ... </div>
</div>
<div class="content-wrapper">
<div class="content"> ... </div>
<div class="actions"> ... </div>
</div>
</div>

这里我需要包装器,因为 header 的布局与内容和操作所在的区域不同。

显而易见的解决方案可能是引入一个 Body 组件,但是有没有更优雅的方法来从 Page 声明的逻辑组件(Header、Content、Actions)中抽象出表示特定布局所需的具体 div 树.

另一个可行的解决方案是按照 React 文档中的建议将 header 、内容和操作作为属性传递:

<Page
header={
<Header> ... </Header>
}
content={
<Content> ... </Content>
}
actions={
<Actions> ... </Actions>
}
/>

谢谢,乔治

最佳答案

React 让您可以访问单个 Children

<Page>
<Header> ... </Header>
<Content> ... </Content>
<Actions> ... </Actions>
</Page>

内部<Page />组件渲染

render() {
// when multiple elements are passed children prop is an array.
// extract each of the element passed from the array and place them
// wherever needed in the JSX
const [HeaderView, ContentView, ActionsView] = this.props.children;

<div class="page">
<div class="header-wrapper>
{HeaderView}
</div>
<div class="content-wrapper">
{ContentView}
{ActionsView}
</div>
</div>
}

关于reactjs - 渲染 React 嵌套组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40986450/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com