Skip to content

Commit 2f51b76

Browse files
committed
2019.09.19
1 parent 5400abf commit 2f51b76

2 files changed

Lines changed: 61 additions & 0 deletions

File tree

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
2+
## 一、组件
3+
4+
React 定义组件的方式有:`React.Component``React.PureComponent`
5+
6+
### 1.React.Component
7+
8+
通过继承 React 基类进行定义:
9+
10+
```js
11+
class LEOComponent extends React.Component {
12+
constructor(props) {
13+
super(props);
14+
this.state = {
15+
};
16+
}
17+
}
18+
```
19+
20+
### 2.React.PureComponent
21+
22+
`React.Component`
23+
24+
### 3.从源码看两者区别
25+
26+
以下是两者实现源码:
27+
28+
```js
29+
function Component(props, context, updater) {
30+
this.props = props;
31+
this.context = context;
32+
this.refs = emptyObject;
33+
this.updater = updater || ReactNoopUpdateQueue;
34+
}
35+
36+
Component.prototype.isReactComponent = {};
37+
Component.prototype.setState = function(partialState, callback) {
38+
// 省略...
39+
};
40+
Component.prototype.forceUpdate = function(callback) {
41+
// 省略...
42+
};
43+
44+
function ComponentDummy() {}
45+
ComponentDummy.prototype = Component.prototype;
46+
47+
function PureComponent(props, context, updater) {
48+
this.props = props;
49+
this.context = context;
50+
this.refs = emptyObject;
51+
this.updater = updater || ReactNoopUpdateQueue;
52+
}
53+
const pureComponentPrototype = (PureComponent.prototype = new ComponentDummy());
54+
pureComponentPrototype.constructor = PureComponent;
55+
Object.assign(pureComponentPrototype, Component.prototype);
56+
pureComponentPrototype.isPureReactComponent = true;
57+
58+
export {Component, PureComponent};
59+
```
60+
61+
从源码看, `React.Component``React.PureComponent` 类实现的方式一样,并且`React.PureComponent` 继承于 `React.Component`,但比 `React.Component` 原型链上多了 `isPureReactComponent` 属性。
66.8 KB
Loading

0 commit comments

Comments
 (0)