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}
  • 相关阅读:
    AngularJS--过滤器
    AngularJS--自定义指令和模板
    AngularJS多模块开发
    百度优先收录HTTPS网站?你的网站https还在等什么
    什么是HTTPS
    必须要懂得的密码技术
    如何处理服务器SSL收到了一个弱临时Diffie-Hellman 密钥?
    可以将代码签名证书安装在多台电脑上吗?
    学习第一天
    前端综合知识小集
  • 原文地址:https://www.cnblogs.com/Answer1215/p/9552035.html
Copyright © 2011-2022 走看看