constructor 函数时组件最先执行的函数
复制代码
1
2
3
4
5
6
7
8class childen extends react.Component{ constructor(props){ super(props); this.state={ attr1:"", } } }
一般在constructor函数中都会存在 上述方法,个人对其的理解
constructor():子类继承父类时的构造方法,主要时用以定义this.属性 在react中一些默认的数据可以直接在此处定义
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23import 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>
复制代码
1<span>{this.custom.date}</span>
复制代码
1
2
3
4
5
6</div> </div> ) } }
spuer(): 注意在定义组件的时候可以没用constructor方法,一旦定义,就必须使用spuer方法,这不是react规定的而是es6要求,具体原因如下
转载于:https://www.cnblogs.com/wrhbk/p/11320255.html
最后
以上就是从容小甜瓜最近收集整理的关于react 组件的构造函数的全部内容,更多相关react内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复