栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

在React构造函数中调用super()有什么作用?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

在React构造函数中调用super()有什么作用?

super()
仅在具有构造函数的React组件内部被调用。例如,以下代码不需要超级:

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

但是,如果我们有一个构造函数,那么它

super()
是强制性的:

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

之所以

this
不能被允许之前的原因
super()
是因为
this
super()
调用if未初始化。但是,即使不使用,
this
我们也需要
super()
内部构造函数,因为
ES6class constructors MUST call super if they aresubclasses
。因此,
super()
只要有构造函数,就必须调用。(但是子类不必具有构造函数)。

super(props)
如果必须使用
this.props
,我们可以在构造函数内部调用,例如:

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

我希望我能说清楚。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/383965.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号