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

本文共 1967 字,大约阅读时间需要 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        }      })    )  }}

 

转载于:https://www.cnblogs.com/Answer1215/p/7662795.html

你可能感兴趣的文章
关于mysql中GROUP_CONCAT函数的使用
查看>>
OD使用教程20 - 调试篇20
查看>>
Java虚拟机(JVM)默认字符集详解
查看>>
Java Servlet 过滤器与 springmvc 拦截器的区别?
查看>>
(tmp >> 8) & 0xff;
查看>>
linux命令之ifconfig详细解释
查看>>
NAT地址转换
查看>>
Nhibernate 过长的字符串报错 dehydration property
查看>>
Deque - leetcode 【双端队列】
查看>>
gulp插件gulp-ruby-sass和livereload插件
查看>>
免费的大数据学习资料,这一份就足够
查看>>
clientWidth、clientHeight、offsetWidth、offsetHeight以及scrollWidth、scrollHeight
查看>>
企业级应用与互联网应用的区别
查看>>
itext jsp页面打印
查看>>
Perl正则表达式匹配
查看>>
DB Change
查看>>
nginx --rhel6.5
查看>>
Eclipse Python插件 PyDev
查看>>
selenium+python3模拟键盘实现粘贴、复制
查看>>
第一篇博客
查看>>