zoukankan      html  css  js  c++  java
  • [React] Implement a React Context Provider

    If you have state that needs to exist throughout your application, then you may find yourself passing props all over the application and even "drilling" the prop through components that don't really care about the prop at all. In this lesson, we'll see a sample of a small app that has the "prop drilling problem" and learn how to implement the "Provider pattern" to access context state anywhere in the component tree.

    To implement a context provider for render props:

    class ToggleProvider extends React.Component {
      static contextName = '__toggle__'
      static Renderer = class extends React.Component {
        static childContextTypes = {
          [ToggleProvider.contextName]:
            PropTypes.object.isRequired,
        }
        getChildContext() {
          return {
            [ToggleProvider.contextName]: this.props
              .toggle,
          }
        }
        render() {
          return this.props.children
        }
      }
      render() {
        const {
          children,
          ...remainingProps
        } = this.props
        return (
          <Toggle
            {...remainingProps}
            render={toggle => (
              <ToggleProvider.Renderer
                toggle={toggle}
                children={children}
              />
            )}
          />
        )
      }
    }
    
    function ConnectedToggle(props, context) {
      return props.render(
        context[ToggleProvider.contextName],
      )
    }
    ConnectedToggle.contextTypes = {
      [ToggleProvider.contextName]:
        PropTypes.object.isRequired,
    }

    Modify the code:

  • 相关阅读:
    C++中的static关键字的总结
    2017上海C++面试
    Vim 跳到上次光标位置
    Windows XP Professional产品序列号
    Centos7 安装sz,rz命令
    Xshell里连接VirtualBox里的Centos7
    什么是位、字节、字、KB、MB
    Centos7 tmux1.6 安装
    Centos7 在 Xshell里 vim的配置
    对JDBC的轻量级封装,Hibernate框架
  • 原文地址:https://www.cnblogs.com/Answer1215/p/8058054.html
Copyright © 2011-2022 走看看