react 组件的构造函数

constructor 函数时组件最先执行的函数

class childen extends react.Component{
   constructor(props){
      super(props);
      this.state={
          attr1:"",
      }
  }
}

一般在constructor函数中都会存在 上述方法,个人对其的理解

constructor():子类继承父类时的构造方法,主要时用以定义this.属性 在react中一些默认的数据可以直接在此处定义

import React from 'react';

class Mine extends React.Component {
    constructor(a) {
        super(a);
        this.state = {
            date: new Date().getTime()
        }
        //定义custom 和state并没有什么本质的区别,在都可以通过this都访问,但是推荐使用state 因为在react中 即使我们不定义this.state
        //this下仍会有一个默认的state属性,具体作用暂时没有发现,感兴趣的同学可以深入了解一下
        this.custom = {
            date: new Date().getTime()
        }
        console.log(a);
    }

    componentWillMount() {
        console.log("在渲染前调用",this)
    }

    render() {
        return (
            <div>
                <div className='head'>
                    <span>{this.state.date}</span>
                    <span>{this.custom.date}</span>
                </div>
            </div>
        )
    }
}

spuer(): 注意在定义组件的时候可以没用constructor方法,一旦定义,就必须使用spuer方法,这不是react规定的而是es6要求,具体原因如下

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

江湖行骗老中医

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值