zoukankan      html  css  js  c++  java
  • [React] Validate Compound Component Context Consumers

    If someone uses one of our compound components outside the React.createContext <ToggleContext.Provider />, they will experience a confusing error. We could provide a default value for our context, but in our situation that doesn't make sense. Instead let's build a simple function component which does validation of our contextValue that comes from the <ToggleContext.Consumer />. That way we can provide a more helpful error message.

    import React from 'react'
    import {Switch} from '../switch'
    
    const ToggleContext = React.createContext()
    
    function ToggleConsumer(props) {
      return (
        <ToggleContext.Consumer {...props}>
          {context => {
            if (!context) {
              throw new Error(
                `Toggle compound components cannot be rendered outside the Toggle component`,
              )
            }
            return props.children(context)
          }}
        </ToggleContext.Consumer>
      )
    }
    
    class Toggle extends React.Component {
      static On = ({children}) => (
        <ToggleConsumer>
          {({on}) => (on ? children : null)}
        </ToggleConsumer>
      )
      static Off = ({children}) => (
        <ToggleConsumer>
          {({on}) => (on ? null : children)}
        </ToggleConsumer>
      )
      static Button = props => (
        <ToggleConsumer>
          {({on, toggle}) => (
            <Switch on={on} onClick={toggle} {...props} />
          )}
        </ToggleConsumer>
      )
      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}
  • 相关阅读:
    [产品设计]我对移动互联网产品的观点
    [Android阅读代码]圆形旋转菜单CircleMenu
    [Android代码阅读]分类简介
    [Android学习笔记]Android调试
    [Android]ADT Run时候报错:The connection to adb is down, and a severe error has occured
    [Android学习笔记]使用ListView
    [Android]Button按下后修改背景图
    [.NET Framework学习笔记]一些概念
    ubuntu fcitx 安装 使用
    nyoj-626-intersection set
  • 原文地址:https://www.cnblogs.com/Answer1215/p/9552035.html
Copyright © 2011-2022 走看看