我一直在挖掘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类相比,以这种方式创建类有什么好处?
https://caniuse.com/#search=es6%20class
这与浏览器兼容性有关。确保代码可以在不支持class
sytax的情况下运行,而无需使用像Babel这样的东西。