React 深度学习:ReactBaseClasses

path:packages/react/src/ReactBaseClasses.js

Component

源码

import invariant from 'shared/invariant';
import lowPriorityWarning from 'shared/lowPriorityWarning';

import ReactNoopUpdateQueue from './ReactNoopUpdateQueue';

const emptyObject = {};
if (__DEV__) {
 // do something
}

/**
 * Base class helpers for the updating state of a component.
 */
function Component(props, context, updater) {
  this.props = props;
  this.context = context;
  // If a component has string refs, we will assign a different object later.
  this.refs = emptyObject;
  // We initialize the default updater but the real one gets injected by the
  // renderer.
  this.updater = updater || ReactNoopUpdateQueue;
}

Component.prototype.isReactComponent = {};

/**
 * Sets a subset of the state. Always use this to mutate
 * state. You should treat `this.state` as immutable.
 *
 * There is no guarantee that `this.state` will be immediately updated, so
 * accessing `this.state` after calling this method may return the old value.
 *
 * There is no guarantee that calls to `setState` will run synchronously,
 * as they may eventually be batched together.  You can provide an optional
 * callback that will be executed when the call to setState is actually
 * completed.
 *
 * When a function is provided to setState, it will be called at some point in
 * the future (not synchronously). It will be called with the up to date
 * component arguments (state, props, context). These values can be different
 * from this.* because your function may be called after receiveProps but before
 * shouldComponentUpdate, and this new state, props, and context will not yet be
 * assigned to this.
 *
 * @param {object|function} partialState Next partial state or function to
 *        produce next partial state to be merged with current state.
 * @param {?function} callback Called after state is updated.
 * @final
 * @protected
 */
Component.prototype.setState = function(partialState, callback) {
  invariant(
    typeof partialState === 'object' ||
      typeof partialState === 'function' ||
      partialState == null,
    'setState(...): takes an object of state variables to update or a ' +
      'function which returns an object of state variables.',
  );
  this.updater.enqueueSetState(this, partialState, callback, 'setState');
};

/**
 * Forces an update. This should only be invoked when it is known with
 * certainty that we are **not** in a DOM transaction.
 *
 * You may want to call this when you know that some deeper aspect of the
 * component's state has changed but `setState` was not called.
 *
 * This will not invoke `shouldComponentUpdate`, but it will invoke
 * `componentWillUpdate` and `componentDidUpdate`.
 *
 * @param {?function} callback Called after update is complete.
 * @final
 * @protected
 */
Component.prototype.forceUpdate = function(callback) {
  this.updater.enqueueForceUpdate(this, callback, 'forceUpdate');
};

复制代码

结构

解析

当 ShoppingList 组件进行实例化的时候它自然也会带有上图中的所有实例属性和原型方法。

使用组件:

<ShoppingList name="Mark" />
复制代码

看到这段代码,产生几个疑问:

  • 继承自 Component 的组件是如何进行实例化的呢?

  • ES6 中继承自其他类的类在实例化的需要显式的调用的 super(),为什么在 React 中不需要呢?

JSX

以上定义 ShoppingList 组件的语法即是 JSX 语法。在 深入 JSX 章节 中讲到,JSX 仅仅只是 React.createElement(component, props, ...children) 函数的语法糖。它最后会被编译为 React.createElement 函数。

例如:

<MyButton color="blue" shadowSize={2}>
  Click Me
</MyButton>
复制代码

会被编译为:

React.createElement(
  MyButton,
  {color: 'blue', shadowSize: 2},
  'Click Me'
)
复制代码

那 JSX 是如何被编译的呢?

在项目中 JSX 被类似 @babel/plugin-transform-react-jsx 的 Babel 插件编译,关于此插件,以后的章节中再进行研究。

最后的一切都指向了 React.createElement 函数,在下一个章节中,我们来探究 React.createElement

PureComponent

源码

/**
 * Deprecated APIs. These APIs used to exist on classic React classes but since
 * we would like to deprecate them, we're not going to move them over to this
 * modern base class. Instead, we define a getter that warns if it's accessed.
 */
if (__DEV__) {
 // do something
}

function ComponentDummy() {}
ComponentDummy.prototype = Component.prototype;

/**
 * Convenience component with default shallow equality check for sCU.
 */
function PureComponent(props, context, updater) {
  this.props = props;
  this.context = context;
  // If a component has string refs, we will assign a different object later.
  this.refs = emptyObject;
  this.updater = updater || ReactNoopUpdateQueue;
}

const pureComponentPrototype = (PureComponent.prototype = new ComponentDummy());
pureComponentPrototype.constructor = PureComponent;
// Avoid an extra prototype jump for these methods.
Object.assign(pureComponentPrototype, Component.prototype);
pureComponentPrototype.isPureReactComponent = true;

export {Component, PureComponent};
复制代码

结构

PureComponent 基本跟 Component 相同

class 组件的编译

下面来看看一个 class 组件:

class Hello extends React.Component {
  
  handleClick(e) {
    console.log('click');
  }
  
  render() {
    function sayHi() { return (<div>Hi</div>); }
    
    return (
      <div>
        { sayHi() }
        Hello { this.props.name }
        <p className="title" onClick={ this.handleClick }>React</p>
        <p className="content">React is cool!</p>
        <MyFooter className="footer">
          <div className="concat">concat</div>
          <div className="info">company info</div>
        </MyFooter>
      </div>
    );
  }
}
复制代码

编译结果:

class Hello extends React.Component {
  handleClick(e) {
    console.log('click');
  }

  render() {
    function sayHi() {
      return React.createElement("div", null, "Hi");
    }

    return React.createElement("div", null, sayHi(), "Hello ", this.props.name, React.createElement("p", {
      className: "title",
      onClick: this.handleClick
    }, "React"), React.createElement("p", {
      className: "content"
    }, "React is cool!"), React.createElement(MyFooter, {
      className: "footer"
    }, React.createElement("div", {
      className: "concat"
    }, "concat"), React.createElement("div", {
      className: "info"
    }, "company info")));
  }

}
复制代码

可以看到,编译器并不会处理类本身,而是将其中的创建 React 元素的语句全局转换成了 React.createElement 函数调用的方式。这时候发现自己以前的知识有误区,遂查看了 @babel/plugin-transform-react-jsx 官方文档,描述中写着:

Turn JSX into React function calls

将 JSX 转换为 React 函数调用,那到底什么是 JSX?是函数组件?class 组件?的所有代码都是 JSX 吗?请参见 React 深入学习:JSX


转载于:https://juejin.im/post/5d118384f265da1bbe5e116c

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值