React.createClass vs extends Component

前端 未结 4 794
长发绾君心
长发绾君心 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:23

    One major differentiator not mentioned above is how the state is inherited when using createClass vs extending a Component.

    var BaseComponent extends Component {
      constructor(props) {
        super(props);
        this.state = {
          foo: 'bar'
        };
      }
    });
    
    var BaseClass = React.createClass({
      getInitialState() {
        return {
          foo: 'bar'
        };
      }
    });
    
    class Test extends BaseClass { // or extend BaseComponent
      constructor(props){
        super(props);
        this.state = {
          ...this.state,
          myNewVar: 'myNewVal'
        }
    
      render() {
        alert(this.state.foo)
      }
    }
    

提交回复
热议问题