美文网首页
谈谈react里面的constructor

谈谈react里面的constructor

作者: 转移到CSDN名字丹丹的小跟班 | 来源:发表于2021-03-13 23:24 被阅读0次

在初学react的时候,每次都将构造器constructor写出来,但是又不懂实际的含义。官网上的描述:如果不初始化 state 或不进行方法绑定,则不需要为 React 组件实现构造函数。这样看来,只有两种情况需要写constructor。

1,初始化 state

class Demo extends React.Component {
  constructor() {
    super()
    this.state = {name: 'dandan'}
  }
  render() {
    return (
      <div>
        测试
      </div>
    );
  }
}

2,进行方法绑定

class Demo extends React.Component {
  constructor() {
    super()
    this.state = {name: 'dandan'}
    this.log = this.log.bind(this)
  }
  render() {
    return (
      <div>
        <button onClick={this.log}>按钮</button>
      </div>
    );
  }
  log() {
    console.log('被点击了')
  }
}

若不存在以上两种情况,constructor构造器可以省略不写

那么在构造器里和super里传与不传props有什么影响呢?

有以下几种情况:

1.都传props

constructor(props) {
    super(props)
    console.log(this.props)  //此处输出props对象
  }

2.都不传props

constructor() {
    super()
    console.log(this.props)  //此处输出undefined
  }
  1. 构造器传但是super不传props
constructor() {
    super()
    console.log(this.props)  //此处输出undefined
  }
  1. 构造器不传但是super传props
constructor() {
    super(props)
    console.log()  //报错
  }

由此看出,构造器里是否接收props参数,是否传递给super,取决于你是否希望在构造器里通过this方法props

相关文章

  • 谈谈react里面的constructor

    在初学react的时候,每次都将构造器constructor写出来,但是又不懂实际的含义。官网上的描述:如果不初始...

  • constructor里用this.props没效果

    在react-native里面的constructor不能使用this.props.xxx。 因为this还没有传...

  • react数据

    react数据是存在state里面的,在constructor方法里面 父子组件传值放在super(props)这...

  • React生命周期

    挂在 constructor()[https://react.docschina.org/docs/react-c...

  • React constructor

    React 中的constructor 以前一直觉得constructor必须声明,否则会造成无法获取到this....

  • React setState 同步异步

    class Example extends React.Component { constructor() { ...

  • React中constructor及super

    constructor( ) 在React中constructor表示父类的构造方法,用来新建父类的this对象,...

  • constructor()

    constructor里的this.state和直接写this.state区别?答案:没有区别 在React中co...

  • 前端面试详解

    React篇 1.react有哪几个生命周期? constructor() static getDerivedSt...

  • react 17生命周期

    Mounting constructor()[https://reactjs.org/docs/react-com...

网友评论

      本文标题:谈谈react里面的constructor

      本文链接:https://www.haomeiwen.com/subject/mmgaqltx.html