docs人中学习React并遇到以下示例:

class Square extends React.Component {
  constructor() {
    super();
    this.state = {
      value: null,
    };
  }
  ...
}

根据Mozilla,super允许在构造函数中使用this.使用独立的super(我知道super也允许您访问父类的方法)还有其他原因吗?但是使用React,是否有其他只调用super()的用例?

推荐答案

只有当react组件具有构造函数时,才会在其内部调用super().例如,下面的代码不需要super:

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()

    }
}

super()之前不能允许this的原因是,如果不调用super(),则this未初始化.然而,即使我们不使用this,我们也需要在构造函数中使用super(),因为ES6 class constructors MUST call super if they are subclasses.因此,只要有构造函数,就必须调用super().(但子类不必有构造函数.)

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

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

    }
}

我希望我能说清楚.

Reactjs相关问答推荐

在带有和设计的表格中禁用和取消选中复选框

使用Overpass API Endpoint计算 map 上的面积

TypeError:b不是React.js中的函数错误

为什么我的React App.js只在页面刷新时呈现3次?

使用REACT-RUTER-V6和ZUSTANDreact 中的身份验证

这两个子元素在Reaction Native中使用的有什么不同?

是否为Reaction中未使用的组件生成Tailwincss样式?

如何删除 bootstrap 手风琴上的边框

状态改变不会触发重新渲染

在reduce()方法上得到NaN

我发送的 prop 的值不会改变.如果成功登录,导航栏中的 prop 必须为 true.我从后端得到 200 ok

React Native - 如何处理错误带有有效负载的NAVIGATE操作..未被任何导航器处理?

React Native 背景动画反转

我正在通过 API(有效)从 MongoDB 传递数据.可视化但我不断收到此 TypeError: Cannot convert undefined or null to object

react 事件顺序

如何在 React 中单击鼠标的位置动态添加 div?

在 React 中,为什么不能向空片段添加键(短语法)?

在 redux 状态更改时更新react 按钮禁用状态

调用函数以获取数据并在数据到达时导航到链接

如何在 React x 中返回组件?