博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[React] Write Compound Components
阅读量:6368 次
发布时间:2019-06-23

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

Compound component gives more rendering control to the user. The functionality of the component stays intact while how it looks and the order of the children can be changed at will. We get this functionality by using the special React.Children.map function to map over the children given to our <Toggle/> component. We map over the children to pass the on state as a prop to its children. We move the visual pieces of the component out into function components and add them as static properties to <Toggle/>.

 

User has free control how On / Off / Button shows on the page:

console.log("Toggle", on)}>
Switch is On!
Switch is Off!
;

 

Toggle.On, Toggle.Off and Toggle.Button is private components for Toggle:

class Toggle extends React.Component {  // An empty function  static defaultProps = {onToggle: () => {}};  static On = ToggleOn;  static Off = ToggleOff;  static Button = ToggleButton;  ....}

 

All those components have props, which user doesn't need to care about, those props should be passed down fromt the parent component: Toggle:

const ToggleOn = ({on, children}) => {  if(on) {    return (
{children}
) } else { return null; }};const ToggleOff = ({on, children}) => { if(on) { return null; } else { return (
{children}
); }};const ToggleButton = ({on, toggle, ...props}) => (
);

This can be done by using React.Children.map and React.cloneElement:

render() {    const {on} = this.state;    const children = React.Children.map(        this.props.children,        (child) => React.cloneElement(child, {            on: this.state.on,            toggle: this.toggle        })    );    return (        
{children}
) }

 

 

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

你可能感兴趣的文章
[BZOJ1588]营业额统计(Splay)
查看>>
[BZOJ 4869][SHOI&SXOI2017]相逢是问候(扩展欧拉定理+线段树)
查看>>
2017-08-13
查看>>
条件语句优化面面观
查看>>
集成友盟微信登录没有回调
查看>>
在CentOS Linux系统上,添加新的端口,启用ssh服务
查看>>
dbcp数据库连接池简单使用
查看>>
leetcode-38-Count and Say
查看>>
从零开始写一个node爬虫(上)—— 数据采集篇
查看>>
java调用远程服务器shell脚本
查看>>
贪吃蛇
查看>>
前端MVC学习总结(四)——NodeJS+MongoDB+AngularJS+Bootstrap书店示例
查看>>
Myeclipse快捷键集合
查看>>
linux安装ftp
查看>>
[转]解读ASP.NET 5 & MVC6系列(8):Session与Caching
查看>>
js正则匹配中文
查看>>
中介者模式(Mediator)
查看>>
Entity Framework 数据生成选项DatabaseGenerated
查看>>
jquery 兼容的滚轮事件
查看>>
模板小例子
查看>>