Open
Description
�pureComponent vs Component vs Stateless Functional component的区别
1,createClass,没有使用es6语法的时候,定义组件,就使用React.createClass来定义组件
var React = require("react");
var Greeting = React.createClass({
propTypes: {
name: React.PropTypes.string //属性校验
},
getDefaultProps: function() {
return {
name: 'Mary' //默认属性值
};
},
getInitialState: function() {
return {count: this.props.initialCount}; //初始化state
},
handleClick: function() {
//用户点击事件的处理函数
},
render: function() {
return <h1>Hello, {this.props.name}</h1>;
}
});
module.exports = Greeting;
在createClass中,React对属性中的所有函数都进行了this绑定,也就是上面的handleClick其实相当于handleClick.bind(this);
2, component,因为es6对类和继承有语法级别的支持,所以用es6创建组件的方式更为优雅
import React from 'react';
class Greeting extends React.Component {
constructor(props) {
super(props); //调用父类的构造函数
this.state = {count: props.initialCount};
this.handleClick = this.handleClick.bind(this);
}
//static defaultProps = {
// name: 'Mary' //定义defaultprops的另一种方式
//}
//static propTypes = {
//name: React.PropTypes.string
//}
handleClick() {
//点击事件的处理函数
}
render() {
return <h1>Hello, {this.props.name}</h1>;
}
}
Greeting.propTypes = {
name: React.PropTypes.string
};
Greeting.defaultProps = {
name: 'Mary'
};
export default Greating;
3,pureComponent
我们知道,当组件的props或者state发生变化时,React就会对当前的props和state分别与nextProps和nextState进行比较,当发生变化时,就会对当前组件或子组件进行重新渲染,否则就不渲染,有时候为了避免租金进行不必要的重新渲染,我们通过shouldComponentUpdate来优化性能
class CounterButton extends React.Component {
constructor(props) {
super(props);
this.state = {count: 1};
}
shouldComponentUpdate(nextProps, nextState) {
if (this.props.color !== nextProps.color) {
return true;
}
if (this.state.count !== nextState.count) {
return true;
}
return false;
}
render() {
return (
<button
color={this.props.color}
onClick={() => this.setState(state => ({count: state.count + 1}))}>
Count: {this.state.count}
</button>
);
}
}
shouldComponentUpdate通过判断props.color和state.count是否发生变化来重新渲染组件,React提供了PureComponent来自动帮我们做这件事,
class CounterButton extends React.PureComponent {
constructor(props) {
super(props);
this.state = {count: 1};
}
render() {
return (
<button
color={this.props.color}
onClick={() => this.setState(state => ({count: state.count + 1}))}>
Count: {this.state.count}
</button>
);
}
}
4,Stateless Functional Component
上面提到的是用来创建包含状态和用户交互的复杂组件,当组件本身只是用来展示,所有数据都是通过props传入的时候,我们便可以使用Stateless Functional Component来快速创建组件
import React from 'react';
const Button = ({
day,
increment
}) => {
return (
<div>
<button onClick={increment}>Today is {day}</button>
</div>
)
}
Button.propTypes = {
day: PropTypes.string.isRequired,
increment: PropTypes.func.isRequired,
}
选哪个
createClass, 除非你确实对ES6的语法一窍不通,不然的话就不要再使用这种方式定义组件。
Stateless Functional Component, 对于不需要内部状态,且用不到生命周期函数的组件,我们可以使用这种方式定义组件,比如展示性的列表组件,可以将列表项定义为Stateless Functional Component。
PureComponent/Component,对于拥有内部state,使用生命周期的函数的组件,我们可以使用二者之一,但是大部分情况下,我更推荐使用PureComponent,因为它提供了更好的性能,同时强制你使用不可变的对象,保持良好的编程习惯。