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:

最新文章

  1. android-配置文件AndroidManifest.xml
  2. 练习JavaScript实现过滤特殊字符
  3. CSS style和HTML style有什么区别?
  4. Python的平凡之路(13)
  5. git如何撤销合并
  6. HDU 3652 B-number
  7. sql server2008中怎样用sql语句创建数据库和数据表
  8. C# DateTime 日期加1天 减一天 加一月 减一月 等方法(转)
  9. Hello Qt
  10. boost库的使用(一)
  11. Hibernate(四)
  12. 【&#9733;】SPF(Dijkstra)算法完美教程
  13. java之日志管理
  14. python读取数据库并把数据写入本地文件
  15. docker 删除所有none的镜像
  16. PHP使用Apache中的ab(ApacheBench)测试网站的并发量
  17. docker里面运行jenkins详解
  18. 使用第三方组件(django-redis)创建连接池
  19. VUE 微信开发
  20. Momenta电话面试笔记

热门文章

  1. socket网络编程登录实现及多客户端和服务端的数据交互
  2. Zookeeper入门-Linux环境下异常ConnectionLossException解决
  3. springboot 错误页面的配置
  4. 洛谷 P1524 十字绣
  5. ListCtrl 控件数据动态改动
  6. mysql-过程与函数
  7. Linux 文件系统初步
  8. PAT(B) 101-111-1-2014-03-01
  9. jmeter名词解释之时间(Elapsed Time/ Latency Time/Connection Time)
  10. 高速掌握Lua 5.3 —— I/O库 (1)