[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
        }
      })
    )
  }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值