React.createClass vs extends Component

前端 未结 4 790
长发绾君心
长发绾君心 2020-12-13 03:40

What\'s the different between

var MyClass = React.createClass({...});

To

class MyClass extends React.Component{...}
         


        
4条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-13 04:32

    These two ways depend on if you are using ES6 syntax or not, and they also change the way you set up your initial state.

    When using ES6 classes, You should initialize state in the constructor.

    When using React.createClass you have to use the getInitialState function.

    ES6 Class Syntax:

    class MyComponent extends React.Component {
      constructor(props) {
        super(props);
        this.state = { /* initial state, this is ES6 syntax (classes) */ };
      }
    }
    

    ES5 React.CreateClass syntax:

    var MyComponent = React.createClass({
      getInitialState() {
        return { /* initial state */ };
      },
    });
    

    These will both work the same way to set up initial state.

提交回复
热议问题