React给容器组件传递组件时候,可以进行嵌套传递吗?

我有一个容器组件如下:
image.png

export default function ComponentBase() {
  return <>
    <div class="left">    
    </div>
    
    <div class=right>
    </div>

  </>
}

需求是,使用时候向组件ComponentBase传递组件,左边传递一个,右边传递一个,例如:

<ComponentBase>
    <LeftComp>    
        <MyCustomComp></MyCustomComp>
    </LeftComp>
    <RightComp>    
        <MyCustomComp></MyCustomComp>
    </RightComp>
</ComponentBase>

请问下,React是否可以实现呢?我知道Vue有slot的概念,不知道slot是否可以传递组件。

阅读 1.5k
2 个回答

直接传两个children 是最简单的做法。
可以这么使用:

export default function ComponentBase({children}) {
  return (<>
    <div class="left">    
         {children[0]}
    </div>
    
    <div class=right>
         {children[1]}
    </div>

  </>)
}

使用

...
return (
    <ComponentBase>
        <div>我是大儿</div>
        <div>我是二儿</div>
    </ComponentBase>
)

或者比较语义化就这样

export default function ComponentBase({renderLeft,renderRight}) {
  return (<>
    <div class="left">    
         {renderLeft}
    </div>
    
    <div class=right>
         {renderRight}
    </div>

  </>)
}

可以把组件当作参数传进去

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题