Javascript 制作react components es6语法时,为什么要使用道具进行超级初始化?
我想我不太擅长JavaScript。Javascript 制作react components es6语法时,为什么要使用道具进行超级初始化?,javascript,reactjs,Javascript,Reactjs,我想我不太擅长JavaScript。 这就是我所看到的初始化react组件的方式。初始设置状态在构造函数中完成。 导出类计数器扩展React.Component{ 构造器(道具){ 超级(道具); this.state={count:props.initialCount}; } 为什么总是有一个super(props)。这是必需的吗?调用super有必要吗?如果不调用super会发生什么情况?只有当您想在类的构造函数中访问这个.props时,才需要在super中传递props class Bas
这就是我所看到的初始化react组件的方式。初始设置状态在构造函数中完成。
导出类计数器扩展React.Component{
构造器(道具){
超级(道具);
this.state={count:props.initialCount};
}
为什么总是有一个
super(props)
。这是必需的吗?调用super有必要吗?如果不调用super会发生什么情况?只有当您想在类的构造函数中访问这个.props时,才需要在super中传递props
class Base extends React.Component {
constructor(props) {
console.log('Base', props);
}
render() {
return <div>Base {this.props.name}</div>;
}
}
class Sub extends Base {
constructor(props) {
super({
name: 'New name prop'
});
console.log('Sub', arguments);
}
}
var sub = <Sub name="Gomic" />
React.render(sub, document.getElementById('container'));
类基扩展React.Component{
建造师(道具){
console.log('Base',道具);
}
render(){
返回基{this.props.name};
}
}
类子扩展基{
建造师(道具){
超级({
名称:“新名称道具”
});
log('Sub',参数);
}
}
var sub=
React.render(sub,document.getElementById('container');
默认情况下,道具不在构造函数中分配。它们在React.createElement方法中分配。因此,只有当超类的构造函数手动将Props
分配给this.Props
时,才应调用super(道具)
。当您仅扩展React.Component
调用super(道具)时
方法对道具不起作用
参考资料:
哦,谢谢,这很有意义。如果根本不调用super()
会发生什么?super只是相当于ES5中的getInitialState()