[译]React ES6 class constructor super()

原博文地址: http://cheng.logdown.com/posts/2016/03/26/683329ide

当咱们像下面这样使用ReactES6 class语法建立一个组件的时候:post

class MyClass extends React.component {
    constructor(){
        super()
    }
}

不由会提出两个问题:this

  1. constructor里面调用super是不是必要的?code

  2. supersuper(props)的区别?component

解答一:

仅当存在constructor的时候必须调用super,若是没有,则不用get

若是在你声明的组件中存在constructor,则必需要加super,举个栗子:it

class MyClass extends React.component {
    render(){
        return <div>Hello { this.props.world }</div>;
    }
}

这段代码完美无误,你不须要为之去调用super,然而,若是在你的代码中存在consturctor,那你必须调用console

class MyClass extends React.component {
    constructor(){
        console.log(this) //Error: 'this' is not allowed before super()

    }
}

之因此会报错,是由于若不执行super,则this没法初始化。class

你也许会抱着侥幸心理猜想:那我直接写个空的constructor就得了呗~,然而,在ES6中的class语法中,只要你的class是子类,那必须得调用super,换句话说,有constructor就得有super(固然,子类也能够没有constructor语法

解答二

仅当你想在constructor内使用props才将props传入superReact会自行props设置在组件的其余地方(以供访问)。
props传入super的做用是能够使你在constructor内访问它:

class MyClass extends React.component{
    constructor(props){
        super();
        console.log(this.props); // this.props is undefined

    }
}

完善后:

class MyClass extends React.component{
    constructor(props){
        super(props);
        console.log(this.props); // prints out whatever is inside props

    }
}

若是你只是想在别处访问它,是没必要传入props的,由于React会自动为你设置好:

class MyClass extends React.component{
    render(){
        // There is no need to call `super(props)` or even having a constructor 

        // this.props is automatically set for you by React 

        // not just in render but another where else other than the constructor

        console.log(this.props);  // it works!

    }
}
相关文章
相关标签/搜索