[译]React ES6 class constructor super()

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

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

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

不禁会提出两个问题:

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

  2. supersuper(props)的区别?

解答一:

仅当存在constructor的时候必须调用super,如果没有,则不用

如果在你声明的组件中存在constructor,则必须要加super,举个栗子:

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

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

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

    }
}

之所以会报错,是因为若不执行super,则this无法初始化。

你也许会抱着侥幸心理猜测:那我直接写个空的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!

    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值