React.createClass与React.Component区别
this
自绑定
React.createClass
创建的组件,其每一个成员函数的this
都有React自动绑定,任何时候使用,直接使用this.method
即可,函数中的this
会被正确设置。
1
2
3
4
5
6
7
8
9
10const Clazz = React.createClass({
handleClick() {
console.log(this); // React Component instance
},
render() {
return (
<div onClick={this.handleClick}></div>
);
}
});
React.Component
创建的组件,其成员函数不会自动绑定this
,需要开发者手动绑定,否则this
不能获取当前组件实例对象。
1
2
3
4
5
6
7
8
9
10
11
12
13class Clazz extends React.Component {
constructor(props) {
super(props);
}
handleClick() {
console.log(this); // null
}
render() {
return (
<div onClick={this.handleClick}></div>
);
}
}
React.Component
有三种手动绑定方法:可以在构造函数中完成绑定,也可以在调用时使用method.bind(this)
来完成绑定,还可以使用Arrow Function(箭头函数)来绑定。
1
2
3
4constructor(props) {
super(props);
this.handleClick = this.handleClick.bind(this); //构造函数中绑定
}
<div onClick={this.handleClick.bind(this)}></div> //使用bind来绑定
<div onClick={()=>this.handleClick()}></div> //使用Arrow Function来绑定
组件初始状态state
的配置不同
React.createClass
创建的组件,其状态state
是通过getInitialState
方法来配置组件相关的状态。
1
2
3
4
5
6
7
8
9
10
11const Clazz = React.createClass({
// return an object
getInitialState(){
return {
isEditing: false
}
}
render(){
return <div></div>
}
})
React.Component
创建的组件,其状态state
是在constructor
中像初始化组件属性一样声明的。
1
2
3
4
5
6
7
8
9
10
11class Clazz extends React.Component{
constructor(props){
super(props);
this.state = { // define this.state in constructor
isEditing: false
}
}
render(){
return <div></div>
}
}
组件属性类型propTypes
及其属性defaultProps
配置不同
React.createClass
在创建组件时,有关组件props
的属性类型及组件默认的属性会作为组件实例的属性来配置,其中defaultProps
是使用getDefaultProps
的方法来获取默认组件属性的。
1
2
3
4
5
6
7
8
9
10
11
12
13const Clazz = React.createClass({
propTypes: { // as an object
name: React.PropTypes.string
},
getDefaultProps(){ // return a object
return {
name: ''
}
}
render(){
return <div></div>
}
})
React.Component
在创建组件时配置这两个对应信息时,他们是作为组件类的属性,不是组件实例的属性,也就是所谓的类的静态属性来配置的。
1
2
3
4
5
6
7
8
9
10class TodoItem extends React.Component {
static propTypes = { //类的静态属性
name: React.PropTypes.string
};
static defaultProps = { //类的静态属性
name: ''
};
...
}