class 是ES6中的写法,如果想要创建组件却不使用ES6,那就使用(ES5)createClass。
前者组件的初始化在constructor中,而后者没有constructor,但额外提供了一个getInitialState方法,用于初始化state,使用createClass需要先安装:npm install --save create-react-class
使用:
var Counter = createClass({
getInitialState:function(){
console.log( ' getInitialState');
return {
k:123
}
},
componentWillMount:function() {
console.log( ' componentWillMount');
console.log(this.state)
},
render: function() {
return <div>{999}</div>;
}
})
区别比较:
class Counter2 extends React.Component{
render(){
return <div>{this.props.k}</div>;
}
}
Counter2.defaultProps = {
k:123
};
var Counter = createClass({
getDefaultProps:function(){
return {
k:123
}
},
render: function() {
return <div>{this.props.k}</div>;
}
});
网友评论