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. Mac下Eclipse/adb无法调试MX5手机

    前提是环境已经配置好,其他手机可以连接但MX系列不可以 解决方法:打开终端 echo 0x2a45 >> ~/.android/adb_usb.ini adb kill-server ad ...

  2. 使用Intellij IDEA的Bookmarks

    用idea的时候,无意中发现了了一个小功能,叫做BookMark Ctrl+F11按出来的然后去查阅了一下文档,主要功能也就是可以清晰的看到自己标的书签附近的代码,比如我们在第11行按一下F11插入一 ...

  3. ar - 建立, 修改档案或从档案中抽取成员.

    总览 ar [-]{dmpqrtx}[abcfilNoPsSuvV] [membername] [count] archive files... 描述 GNU 组织的ar 程序 用于建立, 修改档案 ...

  4. webstorm 创建es6项目 babel 转 es5

    node 安装 webstorm 安装 略过 npm install -y //生成package.json npm install babel-cli -g //全局安装babel-cli npm ...

  5. 修改qq热键后 安全设置-》自动锁定设置 就能保存住qq的热键了

  6. python类访问限制

    1.类的访问限制:要让内部属性不被外部访问,可以把在属性的名称前加上两个下划线__,在Python中,实例的变量名如果以__开头,就变成了一个私有变量(private),只有内部可以访问,外部不能访问 ...

  7. JAVA基础——生产者消费者问题

    1.生产者消费者问题:经典案例 生产者和消费者问题是操作系统的经典问题,在实际工作中也常会用到,主要的难点在于协调生产者和消费者,因为生产者的个数和消费者的个数不确定,而生产者的生成速度与消费者的消费 ...

  8. <Redis> 入门五 持久化RBD/AOF

    RDB RDB持久化是指在指定的时间间隔内将内存中的数据集快照写入磁盘(默认是 dump.rdb). 默认持久化机制,就是将内存中的数据以快照的方式写入二进制文件dump.rbd中. 触发快照的条件 ...

  9. mybatis中<![CDATA[]]>的作用

    此篇文章引自QH_JAVA的文章 在使用mybatis 时我们sql是写在xml 映射文件中,如果写的sql中有一些特殊的字符的话,在解析xml文件的时候会被转义,但我们不希望他被转义,所以我们要使用 ...

  10. 安装配置Keepalived

    一.在haproxy容器安装Keepalived 1.进入haproxy容器: docker exec -it h1 bash 2.apt-get update(因为haproxy容器为Ubuntu) ...