man*_*ain 31 javascript super ecmascript-6 reactjs
我正在学习文档的反应,但不确定super()这个例子中的作用.通常,是否需要传递给生成新实例的参数,然后调用React.Component的构造函数方法将这些参数合并到实例中?没有任何争论,它会做什么?
class LikeButton extends React.Component {
constructor() {
super();
this.state = {
liked: false
};
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
this.setState({liked: !this.state.liked});
}
render() {
const text = this.state.liked ? 'liked' : 'haven\'t liked';
return (
<div onClick={this.handleClick}>
You {text} this. Click to toggle.
</div>
);
}
}
ReactDOM.render(
<LikeButton />,
document.getElementById('example')
);
Run Code Online (Sandbox Code Playgroud)
小智 48
在ES6中,super()如果派生类具有构造函数,则必须调用它们.在react中,所有组件都从Component类扩展.
实际上,每个ES6/react类都不需要构造函数.如果没有定义自定义构造函数,它将使用默认构造函数.对于基类,它是:
constructor() {}
Run Code Online (Sandbox Code Playgroud)
对于派生类,默认构造函数是:
constructor(...args) {
super(...args);
}
Run Code Online (Sandbox Code Playgroud)
您还需要super()在访问之前调用this,因为在调用之前this未初始化super().
在react中使用自定义构造函数有几个原因.一个是您可以this.state = ...使用getInitialState生命周期方法而不是使用生命周期方法在构造函数中设置初始状态.
您还可以在构造函数中绑定类方法this.someClassMethod = this.someClassMethod.bind(this).实际上,在构造函数中绑定方法更好,因为它们只会被创建一次.否则,如果您调用bind或使用箭头函数将方法绑定到构造函数之外的任何位置(如render方法中),它实际上最终将在每个渲染上创建函数的新实例.在这里阅读更多相关信息.
如果要this.props在构造函数中使用,则需要super使用props作为参数调用:
constructor(props) {
super(props);
this.state = {count: props.initialCount};
}
Run Code Online (Sandbox Code Playgroud)
如果不这样做,那么this.props在构造函数中是未定义的.但是,您仍然可以访问this.props构造函数之外的类中的任何其他位置,而无需在构造函数中对其执行任何操作.
Wil*_*een 14
super()javascript中的关键字用于调用父类的方法.这通常在构造函数中用于调用父构造函数.例如:
class Animal {
constructor(age) {
console.log('Animal being made');
this.age = age;
}
returnAge() {
return this.age;
}
}
class Dog extends Animal {
constructor (age){
super(age);
}
logAgeDog () {
console.log(`This dog is: ${ super.returnAge()} years old`);
}
}
const dog = new Dog(5);
console.log(dog);
dog.logAgeDog();Run Code Online (Sandbox Code Playgroud)
在这个例子中,我们有一个Dog类,它extends是一个Animal类.Dog类使用super关键字两次.第一个出现在构造函数中,当super()在构造函数中使用它时,它将调用父类构造函数.因此,我们必须将年龄属性作为参数.现在,狗成功拥有年龄属性.
我们也可以super()在构造函数外部使用,以访问父类的"类"(即原型)属性和方法.我们logAgeDog在Dog类的函数中使用它.我们使用以下代码:
super.returnAge();
Run Code Online (Sandbox Code Playgroud)
你应该读这个:
Animal.returnAge(); // superClass.returnAge()
Run Code Online (Sandbox Code Playgroud)
只有在实现构造函数时才需要super()React中的关键字.您必须执行以下操作:
constructor(props) {
super(props);
// Don't call this.setState() here!
}
Run Code Online (Sandbox Code Playgroud)
命名的父类Component需要自己进行一些初始化,以使React正常工作.如果您实现一个构造函数没有super(props)调用this.props在Component将undefined可导致错误.
| 归档时间: |
|
| 查看次数: |
24566 次 |
| 最近记录: |