【问题标题】:How does props parameter/argument work with constructor keyword work in React?props 参数/参数如何与构造函数关键字一起在 React 中工作?
【发布时间】:2017-09-29 16:57:50
【问题描述】:

有人能解释一下为什么你必须向构造函数提供 props 关键字吗?我认为当您构建组件时,树是自上而下工作的……这意味着道具最终将在子组件中使用。

我记得在一个播客中听到凯尔·辛普森 (Kyle Simpson) 做客时提到,“super”关键字是一种在基于类的系统中获取相对多态引用(从方法到基类)的方法。或者据我了解,这就是语法糖的工作方式,因为在幕后它是一个委托模型。

提前谢谢你!

import React, {Component} from 'react'

class App extends Component {

  constructor(props) {
    super(props)
    this.state = {
      warpDriveCapacity : 10
    }
  }

}

【问题讨论】:

    标签: reactjs


    【解决方案1】:

    如果要在构造函数中使用“this.props”,则需要将 props 传递给 super。否则,没关系,因为 React 在调用构造函数后立即从外部为实例设置了 .props。

    例如:

    export class ComponentName extends Component {
      constructor(props) {
        super(props);
        this.state = {
          stateKey: props.initialProps
        };
      }
      //...
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-26
      • 2021-09-23
      • 2018-05-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多