Our current compound component implementation is great, but it's limited in that users cannot render the structure they need. Let's allow the user to have more flexibility by using React context to share the implicit state to our child <Toggle/> components. We will walk through using React's official context API with React.createContext and use the given Provider and Consumer components to share state implicitly between our compound components giving our users the flexibility they need out of our component.

When we use compound component, we are also using React.Children.map:

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

React.Children.map + this.props.children limits what compound compoment should found some structure, you can do:

  return (
<Toggle onToggle={onToggle}>
<Toggle.On>The button is on</Toggle.On>
<Toggle.Button />
<Toggle.Off>The button is off</Toggle.Off>
</Toggle>
)

But app will break if you do:

  return (
<Toggle onToggle={onToggle}>
<Toggle.On>The button is on</Toggle.On>
<Toggle.Button />
<div>
<Toggle.Off>The button is off</Toggle.Off>
</div>
</Toggle>
)

Because this.props.children will looking for direct child inside <Toggle>, if we add <div> wrapper, it will break the structure, then code won't work.

So we need more flexable code, to achieve that we can use Context.

// Flexible Compound Components with context

import React from 'react'
import {Switch} from '../switch' const ToggleContext = React.createContext() class Toggle extends React.Component { static On = ({children}) => (
<ToggleContext.Consumer>
{contextValue => (contextValue.on ? children : null)}
</ToggleContext.Consumer>
)
static Off = ({children}) => (
<ToggleContext.Consumer>
{contextValue => (contextValue.on ? null : children)}
</ToggleContext.Consumer>
)
static Button = props => (
<ToggleContext.Consumer>
{contextValue => (
<Switch
on={contextValue.on}
onClick={contextValue.toggle}
{...props}
/>
)}
</ToggleContext.Consumer>
)
state = {on: false}
toggle = () =>
this.setState(
({on}) => ({on: !on}),
() => this.props.onToggle(this.state.on),
)
render() { return (
<ToggleContext.Provider
value={{
on: this.state.on,
toggle: this.toggle,
}}
>
{this.props.children}
</ToggleContext.Provider>
)
}
} function Usage({
onToggle = (...args) => console.log('onToggle', ...args),
}) {
return (
<Toggle onToggle={onToggle}>
<Toggle.On>The button is on</Toggle.On>
<Toggle.Off>The button is off</Toggle.Off>
<div>
<Toggle.Button />
</div>
</Toggle>
)
}
Usage.title = 'Flexible Compound Components' export {Toggle, Usage as default}

[React] Make Compound React Components Flexible的更多相关文章

  1. [React] Render Text Only Components in React 16

    In this session we create a comment component to explore how to create components that only render t ...

  2. [React] Recompose: Theme React Components Live with Context

    SASS Bootstrap allows us to configure theme or branding variables that affect all components (e.g. P ...

  3. [react] 细数 React 的原罪

    Props & onChange 的原罪 .「props & onChange 接口规范」它不是一个典型的「程序接口规范」. 当你拿到一个可视组件的 ref,却没有类似 setProp ...

  4. React笔记:React基础(2)

    1. JSX JSX是一种拥有描述UI的JavaScript扩展语法,React使用这种语法描述组件的UI. 1.1 基本语法 JSX可以嵌套多个HTML标签,可以使用大部分符号HTML规范的属性. ...

  5. react初探索--react + react-router + ant-design 后台管理系统配置

    首先确认安装了node环境,Node >= 6. 如果对react 及 ant-design 一无所知,建议去阅读下api文档,react 可以在 codePen 在线练习. react Api ...

  6. react新特性 react hooks

    本文介绍的是react新特性react hooks,本文面向的是有一定react开发经验的小伙伴,如果你对react还不是很熟悉的话我建议你先学习react并多多联系. 首先我们都知道react有3种 ...

  7. react聊天室|react+redux仿微信聊天IM实例|react仿微信界面

    一.项目概况 基于react+react-dom+react-router-dom+redux+react-redux+webpack2.0+react-photoswipe+swiper等技术混合开 ...

  8. WHAT IS THE DIFFERENCE BETWEEN REACT.JS AND REACT NATIVE?

    Amit Ashwini - 09 SEPTEMBER 2017 React.js was developed by Facebook to address its need for a dynami ...

  9. 七天接手react项目 系列 —— react 脚手架创建项目

    其他章节请看: 七天接手react项目 系列 react 脚手架创建项目 前面我们一直通过 script 的方式学习 react 基础知识,而真实项目通常是基于脚手架进行开发. 本篇首先通过 reac ...

随机推荐

  1. 5.4QBXT 模拟赛 (Rank1 机械键盘 蛤蛤)

    NOIP2016提高组模拟赛 ——By wangyurzee7 中文题目名称 纸牌 杯具 辣鸡 英文题目与子目录名 cards cups spicychicken 可执行文件名 cards cups ...

  2. 微信小程序中的图形验证码

    可以在utils中新建一个mcaptcha.js 代码如下: module.exports = class Mcaptcha { constructor(options) { this.options ...

  3. (转)淘淘商城系列——maven工程debug调试

    http://blog.csdn.net/yerenyuan_pku/article/details/72784074 上文我们已经实现了商品列表展示的功能,在实际开发中我们肯定是要经常对maven工 ...

  4. C#反射的使用

    1.先定义个类,编译成dll,用于调用 nameSpace Test{ public class Class1 { private string _name; private int _age; pu ...

  5. 哈尔滨工程大学ACM预热赛 补题

    链接:https://ac.nowcoder.com/acm/contest/554/A来源:牛客网 小虎刚刚上了幼儿园,老师让他做一个家庭作业:首先画3个格子,第二行有2个格子,第三行有1个格子. ...

  6. 模态对话框与非模态对话框(modeless)

    对话框有两种创建方式:DoModal和Creat. 其中DoModal创建的是模态的对话框,而Creat创建的是非模态的对话框下面总结下他们的不同. 对于模态的对话框,在该对话框被关闭前,用户将不能在 ...

  7. Python轮换

    switch_source()用于获取文本信息rewrite_source()用于将信息顺序轮换,其参数times表示要轮换多少次, def switch_source(): tmp = [] wit ...

  8. 什么是MVVM?

    在2008年Chrome V8引擎横空出世,让Javascript的效率有了质的飞跃,天才的Ryan Dahl将V8放到服务器上运行Javascript,Node.js便瓜瓜坠地,Node.js不仅给 ...

  9. vue 接口统一管理

    在外部创建一个API文件夹,然后创建一个API.js  例如 const filmbanner = 'api/billboard/home?__t=1498823077473'; const film ...

  10. [Python3网络爬虫开发实战] 1.5.1-PyMySQL的安装

    在Python 3中,如果想要将数据存储到MySQL中,就需要借助PyMySQL来操作,本节中我们介绍一下它的安装方式. 1. 相关链接 GitHub:https://github.com/PyMyS ...