react中的constructor和super

     经验贴,站在巨人的肩膀上学习,通过查阅资料,结合自己的理解,总结得出规律。
      [1](https://www.cnblogs.com/faith3/p/9219446.html)
      [2](https://www.jianshu.com/p/82966e22a6bd)

1. constructor

我们平常在写react框架是,定义一个类组件,有时候会用到constructor和super,如下图。

export default class App extends Component {
 constructor() {
    super();

     this.state = {
      message: "你好啊"
    }
  }

但很多时候又忽略不写,那这应用在什么场景呢。
查阅资料,直接总结

由ES6的继承规则得知,不管子类写不写constructor,在new实例的过程都会给补上constructor。
所以:constructor钩子函数并不是不可缺少的,子组件可以在一些情况略去。

有constructor钩子函数时候,Child类会多一个constructor方法。可以定义state,如果用户不定义state的话,有无constructor钩子函数时候没有区别。

有constructor钩子函数,定义sate情况

class APP extends React.Component{
              constructor(props){
                super(props);

               this.state={
                
                   counter:0
               }
              }

              render(){
                  return(
                      <div>
                        <h2>当前计数:{this.state.counter}</h2>
                        <button onClick={this.increment.bind(this)} >+1</button>
                        <button onClick={this.decrement.bind(this)}>-1</button>
                      </div>
                  )
              }

没有constructor钩子函数情况

export default class App extends Component {
  render() {
    return (
      <div>
        <ChildCpn name="why" age="18" height="1.88" />
        <ChildCpn name="kobe" age="40" height="1.98" />
      </div>
    )
  }
}

总结:
如果组件要定义自己的state初始状态的话,需要写在constructor钩子函数中,
如果用户不使用state的话,纯用props接受参数,有没有constructor钩子函数都可以,可以不用constructor钩子函数。

2.super
super就跟java里面的用法类似,子类继承父类,需要通过super继承。不然的话会产生报错。

3. props
我们可以看到钩子函数应有有些是有参数有些是无参数的。

无参数

export default class App extends PureComponent {
  
  render() {
  
    return (
      <div>
        APP:{this.props.name}
      </div>
    )
  }
}

只有一个理由需要传递props作为super()的参数,那就是你需要在构造函数内使用this.props

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值