概述
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要求,具体原因如下
转载于:https://www.cnblogs.com/wrhbk/p/11320255.html
最后
以上就是从容小甜瓜为你收集整理的react 组件的构造函数的全部内容,希望文章能够帮你解决react 组件的构造函数所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复