Fork me on GitHub

React Practice Deposit

React.createClass与React.Component区别

this自绑定

React.createClass创建的组件,其每一个成员函数的this都有React自动绑定,任何时候使用,直接使用this.method即可,函数中的this会被正确设置。

1
2
3
4
5
6
7
8
9
10
const 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
13
class 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
4
constructor(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
11
const 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
11
class 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
13
const 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
10
class TodoItem extends React.Component {
static propTypes = { //类的静态属性
name: React.PropTypes.string
};
static defaultProps = { //类的静态属性
name: ''
};

...
}