加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

[译]React ES6 class constructor super()

发布时间:2020-12-15 05:13:00 所属栏目:百科 来源:网络整理
导读:原博文地址: http://cheng.logdown.com/posts/2016/03/26/683329 当我们像下面这样使用 React 的 ES6 class语法创建一个组件的时候: class MyClass extends React.component { constructor(){ super() }} 不禁会提出两个问题: 在 constructor 里面调用 sup

原博文地址: 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!

    }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读