为什么React.Component的内部实现是一个函数而不是一个ES6类?

问题描述 投票:0回答:1

我一直在挖掘React的codebase,我发现当你编写class App extends React.Component时,你实际上正在扩展由以下函数创建的对象:

function Component (props, context, updater) {
  this.props = props;
  this.context = context;
  this.refs = {};
  // We initialize the default updater but the real one gets injected by the
  // renderer.
  this.updater = updater || ReactNoopUpdateQueue ;
}

Component.prototype.isReactComponent = {};

Component.prototype.setState = function(partialState, callback) {
  this.updater.enqueueSetState(this, partialState, callback, 'setState')
}

Component.prototype.forceUpdate = function(callback) {
  this.updater.enqueueForceUpdate(this, callback, 'forceUpdate');
}

与编写ES6类相比,以这种方式创建类有什么好处?

javascript reactjs es6-class
1个回答
1
投票

https://caniuse.com/#search=es6%20class

这与浏览器兼容性有关。确保代码可以在不支持class sytax的情况下运行,而无需使用像Babel这样的东西。

© www.soinside.com 2019 - 2024. All rights reserved.