[React] Compound Component (React.Children.map & React.cloneElement)

Imaging you are building a Tabs component.

If looks like:

复制代码
<Tabs>
    <TabList>
        <Tab> one </Tab>
        <Tab isDisabled> two </Tab>
        <Tab> three </Tab>    
    </TabList>

    <TabPanels>
        <TabPanel>
            content one
        </TabPanel>
        <TabPanel>
            content two
        <TabPanel>
        </TabPanel>
        <TabPanel>
            content three
        </TabPanel>
    </TabPanels>        
</Tabs>
复制代码

You want to know which tab is clicked (actived). But you don't want this actived tab state be exported to our app, you want it been kept to Tabs component. 

For example in Tabs component, there is a state called 'activedIndex':

复制代码
class Tab extends React.Component {
  state = {
    activedIndex: 0
  }

  render() {
return (
    {this.props.children}
  );
} }
复制代码

You want to pass down to TabList and TabPanels componet. And also TabList and TabPanels may receive different props depends on usecases.

You can use 'React.Children.map' to map over each direct child of the componet (in our case is TabPanels and TabList). 

 React.Children.map(this.props.children, (child, index) => {

To pass down the new props, we can use 'React.cloneElement', which need the old props if any, but merge with new props we pass in.

return React.cloneElement(child, {
            activeIndex: this.state.activeIndex
          })

 

Code:

复制代码
class Tab extends React.Component {
  state = {
    activedIndex: 0
  }

  render() {
    return (
      React.Children.map(this.props.children, (child, index) => {
        if (child.type === TabPanels) {
          return React.cloneElement(child, {
            activeIndex: this.state.activeIndex
          })
        } else if(child.type === TabList) {
          return React.cloneElement(child, {
            activeIndex: this.state.activeIndex,
            isActivate: index === this.state.activeIndex
          })
        } else {
          return child
        }
      })
    )
  }
}
复制代码

 

posted @   Zhentiw  阅读(553)  评论(0编辑  收藏  举报
编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
历史上的今天:
2016-10-13 [TypeScript] Creating a Class in TypeScript
2016-10-13 [Angular2 Router] Preload lzay loading modules
2016-10-13 [Yarn] A JavaScript Package Manager
点击右上角即可分享
微信分享提示