React组件中定义static方法有什么作用呢?
今天与人闲聊,突然想到这个问题。于是在Babel中文网,输入以下代码:
import React from 'react'
export default class App extends React.Component {
constructor() {
super()
}
static say() {
console.log('say')
}
run = () => {
console.log('run')
}
render() {
return <div>Hello World.</div>
}
}
上面代码被转译成ES5,得到的结果如下(只粘贴了关键代码):
var App = /*#__PURE__*/function (_React$Component) {
_inherits(App, _React$Component);
var _super = _createSuper(App);
function App() {
var _this;
_classCallCheck(this, App);
_this = _super.call(this);
_defineProperty(_assertThisInitialized(_this), "run", function () {
console.log('run');
});
return _this;
}
_createClass(App, [{
key: "render",
value: function render() {
return /*#__PURE__*/_react.default.createElement("div", null, "hello world.");
}
}], [{
key: "say",
value: function say() {
console.log('say');
}
}]);
return App;
}(_react.default.Component);
可见,static修饰的say函数,作为第三个参数被传入_createClass,之后调用_defineProperties方法。
function _createClass(Constructor, protoProps, staticProps) {
if (protoProps) _defineProperties(Constructor.prototype, protoProps);
if (staticProps) _defineProperties(Constructor, staticProps);
return Constructor;
}
_defineProperties方法中调用Object.defineProperty方法,将say添加为构造函数的属性。
function _defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(target, descriptor.key, descriptor);
}
}
所以静态属性是类的属性,而不是类的实例的属性
网友评论