经验贴,站在巨人的肩膀上学习,通过查阅资料,结合自己的理解,总结得出规律。
[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