Javascript 为什么在react组件中使用此.setState()而不是super.setState()
我是react的新手,我注意到我们使用了Javascript 为什么在react组件中使用此.setState()而不是super.setState(),javascript,reactjs,ecmascript-6,Javascript,Reactjs,Ecmascript 6,我是react的新手,我注意到我们使用了this.setState()而不是super.setState()请我清楚地解释一下为什么我们使用它来调用超类方法?? 例如: class Checkbox extends React.Component { constructor(props) { super(props) this.state = { checked: true }
this.setState()
而不是super.setState()
请我清楚地解释一下为什么我们使用它来调用超类方法??
例如:
class Checkbox extends React.Component {
constructor(props) {
super(props)
this.state = {
checked: true
}
this.handleCheck = this.handleCheck.bind(this)
}
handleCheck() {
this.setState({
checked: !this.state.checked
})
}
render() {
var msg
if(this.state.checked) {
msg = "checked"
} else {
msg = "not checked"
}
return (
<div>
<input type="checkbox"
onChange={this.handleCheck}
defaultChecked={this.state.checked}/>
<p>This box is {msg}</p>
</div>
)
}
}
class复选框扩展了React.Component{
建造师(道具){
超级(道具)
此.state={
核对:正确
}
this.handleCheck=this.handleCheck.bind(this)
}
handleCheck(){
这是我的国家({
选中:!this.state.checked
})
}
render(){
味精
if(this.state.checked){
msg=“选中”
}否则{
msg=“未选中”
}
返回(
这个盒子是{msg}
)
}
}
这就是JavaScript继承的工作原理。Checkbox
子类的实例原型继承自React.Component
父类,this.setState===super.setState
super.method
仅当它在子类中被重写时才应被引用,它通常出现在被重写的方法本身中:
method() {
super.method(); // inherit the behaviour from parent class
// do something else
}
否则,使用super.method()
可能会被视为语义错误,这表明开发人员不了解继承机制。如果一个方法稍后将被重写,它将不会因此而被使用(尽管在setState
的情况下不太可能)
使用super.method()
还需要开发人员了解父类实现。如中所述,只有父原型方法而不是实例方法可用作super
。如果父类有实例方法
method = () => {...}
子类将以
this.method
的形式继承它,但不会有super.method
,因为它继承了超类方法。因此,我们从super继承的每一个东西都可以使用此方法调用它们?只要您不通过在组件中实现该方法来重写它(这从来都不是问题,因为您只实现了自己的生命周期方法,而不应该直接调用这些方法).Inheritation。您只需要在React类构造函数中使用super
关键字,就可以在构造函数中使用this
关键字。您可以使用它访问父类上的方法,但不需要。(这也是在其他语言中继承的工作方式)