注意:结合Context , Provider,Consumer的使用说明阅读,会更有收获

https://www.yuque.com/lijunyang/dk90s4/akf6xn#RrPJp

  1. <!-- /dist/index.html -->
  2. <!doctype html>
  3. <html>
  4. <head>
  5. <title>react</title>
  6. <script src="./react.js"></script>
  7. <script src="./react-dom.js"></script>
  8. </head>
  9. <body>
  10. <div id="root">
  11. </div>
  12. <script>
  13. debugger;
  14. var context = React.createContext('默认值');
  15. var contextProvider = context.Provider;
  16. var contextConsumer = context.Consumer;
  17. var Son = (function (Component) {
  18. Mod.prototype = Object.create(Component.prototype);
  19. Mod.prototype.constructor = Mod;
  20. Mod.__proto__ = Component;
  21. function Mod() {
  22. debugger;
  23. var _this;
  24. _this = Component.apply(this, arguments) || this;
  25. return _this;
  26. }
  27. Mod.prototype.render = function () {
  28. const self = this;
  29. console.log('self', self);
  30. return React.createElement(
  31. 'div',
  32. {
  33. onClick: function () {
  34. self.context.rename('999');
  35. }
  36. },
  37. self.context.value
  38. );
  39. }
  40. return Mod;
  41. }(React.Component))
  42. var ShouldFalse = (function (Component) {
  43. Mod.prototype = Object.create(Component.prototype);
  44. Mod.prototype.constructor = Mod;
  45. Mod.__proto__ = Component;
  46. function Mod() {
  47. var _this;
  48. _this = Component.apply(this, arguments) || this;
  49. _this.shouldComponentUpdate = function () {
  50. // 接受两个参数nextProps,nextState
  51. console.log('shouldComponentUpdate', arguments)
  52. return false; // context子组件可以不受到shouldComponentUpdate的影响
  53. }
  54. return _this;
  55. }
  56. Mod.prototype.render = function () {
  57. const self = this;
  58. console.log('self', self);
  59. return React.createElement(
  60. 'div',
  61. {
  62. onClick: function () {
  63. self.context.rename('888');
  64. }
  65. },
  66. self.context.value
  67. );
  68. }
  69. return Mod;
  70. }(React.Component))
  71. // 注意,这个是关键,没有的话,就不能拿到Context了
  72. Son.contextType = context;
  73. ShouldFalse.contextType = context;
  74. var Parent = (function (Component) {
  75. Mod.prototype = Object.create(Component.prototype);
  76. Mod.prototype.constructor = Mod;
  77. Mod.__proto__ = Component;
  78. function Mod() {
  79. var _this;
  80. _this = Component.apply(this, arguments) || this;
  81. _this.state = {
  82. name: 'TestMod',
  83. errorFlag: false,
  84. };
  85. _this.componentDidMount = function () {
  86. // 没参数
  87. console.log('componentDidMount', arguments)
  88. }
  89. _this.shouldComponentUpdate = function () {
  90. // 接受两个参数nextProps,nextState
  91. console.log('shouldComponentUpdate', arguments)
  92. return true;
  93. }
  94. _this.getSnapshotBeforeUpdate = function () {
  95. // 接受2个参数,return的值作为componentDidUpdate的第三个参数
  96. console.log('getSnapShotBeforeUpdate', arguments)
  97. return { a: 1 };
  98. }
  99. _this.componentDidUpdate = function () {
  100. // 接受3个参数,prevProps,prevState
  101. console.log('componentDidUpdate', arguments)
  102. }
  103. _this.componentDidCatch = function (error, info) {
  104. // 子组件的render发生异常,才会被执行的生命周期
  105. console.log('Parent componentDidCatch', arguments)
  106. _this.setState({
  107. errorFlag: true,
  108. })
  109. }
  110. return _this;
  111. }
  112. var count = 0;
  113. Mod.getDerivedStateFromProps = function () {
  114. if (count === 0) {
  115. console.log('初始化 getDerivedStateFromProps')
  116. } else {
  117. console.log('变更期 getDerivedStateFromProps')
  118. }
  119. return null;
  120. }
  121. Mod.prototype.render = function () {
  122. if (count === 0) {
  123. console.log("初始化 render")
  124. count = 1;
  125. } else {
  126. console.log("变更起 render")
  127. }
  128. const self = this;
  129. var errorFlag = this.state.errorFlag;
  130. return React.createElement(
  131. 'div',
  132. {
  133. key: 'Parent',
  134. id: 'Parent',
  135. },
  136. React.createElement(
  137. contextProvider,
  138. {
  139. value: {
  140. value: self.state.name,
  141. rename: function rename(name) {
  142. self.setState({
  143. name: name
  144. });
  145. }
  146. }
  147. },
  148. React.createElement(Son, null),
  149. React.createElement(ShouldFalse, null),
  150. React.createElement('div', null,
  151. React.createElement(function (props, context) {
  152. console.log('arguments1', arguments); // 它没有props,context
  153. return React.createElement(Son, null); // 它拿到了Context
  154. })
  155. ),
  156. React.createElement(contextConsumer, null, function (props) {
  157. console.log('arguments2', arguments); // 它没有context,但是它拿到了Props
  158. return React.createElement('div', null, props.value)
  159. })
  160. ),
  161. React.createElement(contextProvider, null, // 拿不到默认的value
  162. React.createElement(contextConsumer, null, function () { // 拿不到默认的value
  163. console.log('arguments3', arguments);
  164. return React.createElement('div', null, '111')
  165. })
  166. ),
  167. React.createElement(contextProvider, null, // 它什么都没拿到
  168. React.createElement(function () {
  169. console.log('arguments4', arguments);
  170. return React.createElement('div', null, '111')
  171. })
  172. ),
  173. React.createElement(contextConsumer, null, function (props) { // 只有它才能拿到默认的value
  174. console.log('arguments5', arguments);
  175. return React.createElement('div', null, props)
  176. })
  177. );
  178. }
  179. return Mod;
  180. }(React.Component))
  181. var reactElement = React.createElement(Parent, null);
  182. ReactDOM.render(reactElement, document.getElementById('root'))
  183. </script>
  184. </body>
  185. </html>
function createContext (defaultValue, calculateChangedBits) {
    if (calculateChangedBits === undefined) {
      calculateChangedBits = null;
    } else {
      {
        !(calculateChangedBits === null || typeof calculateChangedBits === 'function') ? warningWithoutStack$1(false, 'createContext: Expected the optional second argument to be a ' + 'function. Instead received: %s', calculateChangedBits) : void 0;
      }
    }

    var context = {
      $$typeof: REACT_CONTEXT_TYPE,
      _calculateChangedBits: calculateChangedBits,
      _currentValue: defaultValue,
      _currentValue2: defaultValue,
      _threadCount: 0,
      Provider: null,
      Consumer: null
    };

    context.Provider = {
      $$typeof: REACT_PROVIDER_TYPE,
      _context: context
    };

    var hasWarnedAboutUsingNestedContextConsumers = false;
    var hasWarnedAboutUsingConsumerProvider = false;

    {
      var Consumer = {
        $$typeof: REACT_CONTEXT_TYPE,
        _context: context,
        _calculateChangedBits: context._calculateChangedBits
      };
      Object.defineProperties(Consumer, {
        Provider: {
          get: function () {
            if (!hasWarnedAboutUsingConsumerProvider) {
              hasWarnedAboutUsingConsumerProvider = true;
              warning$1(false, 'Rendering <Context.Consumer.Provider> is not supported and will be removed in ' + 'a future major release. Did you mean to render <Context.Provider> instead?');
            }
            return context.Provider;
          },
          set: function (_Provider) {
            context.Provider = _Provider;
          }
        },
        _currentValue: {
          get: function () {
            return context._currentValue;
          },
          set: function (_currentValue) {
            context._currentValue = _currentValue;
          }
        },
        _currentValue2: {
          get: function () {
            return context._currentValue2;
          },
          set: function (_currentValue2) {
            context._currentValue2 = _currentValue2;
          }
        },
        _threadCount: {
          get: function () {
            return context._threadCount;
          },
          set: function (_threadCount) {
            context._threadCount = _threadCount;
          }
        },
        Consumer: {
          get: function () {
            if (!hasWarnedAboutUsingNestedContextConsumers) {
              hasWarnedAboutUsingNestedContextConsumers = true;
              warning$1(false, 'Rendering <Context.Consumer.Consumer> is not supported and will be removed in ' + 'a future major release. Did you mean to render <Context.Consumer> instead?');
            }
            return context.Consumer;
          }
        }
      });
      context.Consumer = Consumer;
    }

    {
      context._currentRenderer = null;
      context._currentRenderer2 = null;
    }

    return context;
  }