[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:

 

posted @   Zhentiw  阅读(242)  评论(0编辑  收藏  举报
编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
历史上的今天:
2016-12-18 [React Native] Animate Styles of a React Native View with Animated.timing
2016-12-18 [Compose] 10. Capture Side Effects in a Task
2015-12-18 [Unit Testing] Node testing: Test api Get request
2015-12-18 [CSS3] Interactive Pseudo-Classes :link :visited :hover :active
2015-12-18 [Javascript] Intro to Recursion - Refactoring to a Pure Function
2015-12-18 [Javascript ] Array methods in depth - sort
点击右上角即可分享
微信分享提示