Context

context是在 react @ 0.14 版本以后发布的一个高级且实验性的功能,有可能在未来做出更改。不推荐使用!

使用 Context 的原因

实现 越级传递props

祖父组件

  1. import React, { Component } from 'react'
  2. import propTypes from 'prop-types'
  3. import Father from './Father'
  4. class GrandFather extends Component {
  5. getChildContext(){
  6. return {
  7. hello:"son"
  8. }
  9. }
  10. render(){
  11. return (
  12. <div className="grandFather">
  13. <h1>GrandFather</h1>
  14. <Father />
  15. </div>
  16. )
  17. }
  18. }
  19. GrandFather.childContextTypes = {
  20. hello:propTypes.string
  21. }
  22. export default GrandFather

父组件

  1. import React, { Component } from 'react'
  2. import Son from './Son'
  3. class Father extends Component {
  4. render() {
  5. return (
  6. <div className="father">
  7. <h1>Father</h1>
  8. <Son />
  9. </div>
  10. )
  11. }
  12. }
  13. export default Father

子组件

  1. import React, { Component } from 'react'
  2. import propTypes from 'prop-types'
  3. class Son extends Component {
  4. render() {
  5. console.log(this.context)
  6. return (
  7. <div className="son">
  8. <h1>Son</h1>
  9. <h1>{this.context.hello}</h1>
  10. </div>
  11. )
  12. }
  13. }
  14. Son.contextTypes = {
  15. hello:propTypes.string
  16. }
  17. export default Son