zoukankan      html  css  js  c++  java
  • [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
            }
          })
        )
      }
    }
  • 相关阅读:
    数据持久化的复习
    iOS: 消息通信中的Notification&KVO
    iOS 证书与签名 解惑详解
    数据持久化 技术比较
    iOS开发拓展篇-XMPP简单介绍
    iOS block并发
    Xcode把应用程序打包成ipa
    谈谈用SQLite和FMDB而不用Core Data
    cannot use the same dataset for report.dataset and page.dataset
    cxGRID中的字段怎么能以0.00的格式显示
  • 原文地址:https://www.cnblogs.com/Answer1215/p/7662795.html
Copyright © 2011-2022 走看看