博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[React] Compound Component (React.Children.map & React.cloneElement)
阅读量:5918 次
发布时间:2019-06-19

本文共 1913 字,大约阅读时间需要 6 分钟。

Imaging you are building a Tabs component.

If looks like:

one
two
three
content one
content two
content three

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

 

转载地址:http://yvfvx.baihongyu.com/

你可能感兴趣的文章
解剖SQLSERVER 第八篇 OrcaMDF 现在支持多数据文件的数据库(译)
查看>>
【原】在Matplotlib绘图中添加Latex风格公式
查看>>
[我给Unity官方视频教程做中文字幕]beginner Graphics – Lessons系列之灯光介绍Lights...
查看>>
常见的几个js疑难点,match,charAt,charCodeAt,map,search
查看>>
java实现simhash算法
查看>>
西南大学2012年数学分析考研试题
查看>>
petshop4.0 具体解释之中的一个(系统架构设计)
查看>>
(十三)WebGIS中工具栏的设计之命令模式
查看>>
HDU5086:Revenge of Segment Tree(规律题)
查看>>
IE浏览器窗口合并
查看>>
IOS成长之路-Nsstring中搜索方法rangeOfString
查看>>
移位寄存器
查看>>
C#开发微信门户及应用(12)-使用语音处理
查看>>
与Win8之磁盘活动时间100%斗争心得
查看>>
u盘的一些理解
查看>>
堆区和栈区的区别【转】
查看>>
【Unity3d】火炬之光的X射线效果
查看>>
谈谈GUI的配色和字体选择
查看>>
一个load飙高的过程分析,非常有价值(转)
查看>>
Unity Svn(转)
查看>>