React createClass 和 React.Component 有什么区别?

以前是这样写的

let app = React.createClass({
    getInitialState: function(){
        // some thing
    }
})

然后也看到用 React.Component,于是


class TodoApp extends React.Component{
    getInitialState(){
         // some thing
    }
}

但是压根没有执行 getInitialState,控制台提示

Warning: getInitialState was defined on TodoApp, a plain JavaScript class. This is only supported for classes created using React.createClass. Did you mean to define a state property instead?

其实吧,

React在ES6的实现中去掉了getInitialState这个hook函数,规定state在constructor中实现
官网上有提及两者:

The API (via 'extends React.Component') is similar to React.createClass with the exception of getInitialState. Instead of providing a separate getInitialState method, you set up your own state property in the constructor.

也就是说 通过es6类的继承实现时 state的初始化要在constructor中声明

class exampleComponent extends React.Component {
    constructor(props) {
        super(props);
        this.state = {example: 'example'}
    }
}
posted @ 2016-09-28 12:48  Sameen  阅读(253)  评论(0)    收藏  举报