什么时候传递道具给super()很重要,为什么?
class MyComponent extends React.Component {
constructor(props) {
super(); // or super(props) ?
}
}
什么时候传递道具给super()很重要,为什么?
class MyComponent extends React.Component {
constructor(props) {
super(); // or super(props) ?
}
}
当前回答
这是我做的小提琴:jsfiddle.net。它表明默认情况下道具不是在构造函数中分配的。据我所知,它们是在方法React.createElement中分配的。因此,super(props)应该只在超类的构造函数手动将props赋给this.props时调用。如果你只是扩展React。组件调用super(props)不会对props做任何事情。也许它会在React的下一个版本中被改变。
其他回答
按照源代码
function ReactComponent(props, context) {
this.props = props;
this.context = context;
}
你每次有道具的时候都要传递道具,不要把道具放到这里。手动道具。
对于react 16.6.3版本,我们使用super(props)来初始化状态元素名称:this.props.name
constructor(props){
super(props);
}
state = {
name:this.props.name
//otherwise not defined
};
这里我们不会在构造函数中获取这个,所以它将返回undefined,但是我们可以在构造函数外获取这个
class MyComponent extends React.Component {
constructor() {
console.log(this); // Reference Error i.e return undefined
}
render() {
return <div>Hello {this.props.name}</div>;
}
}
如果我们使用super(),那么我们也可以在构造函数中获取“this”变量
class MyComponent extends React.Component {
constructor() {
super();
console.log(this); // this logged to console
}
render() {
return <div>Hello {this.props.name}</div>;
}
}
当我们使用super();我们可以得到这个,但是这个。Props在构造函数中没有定义。除了构造函数,还有这个。Props不会返回undefined。
如果我们使用super(道具),那么我们可以使用这个。Props在构造函数中的值
苏菲·阿尔珀特的回答
如果你想用这个。构造函数中的道具,需要传递 为超级喝彩。否则,没关系,因为React会设置.props 调用后立即从外部调用实例 构造函数。
在本例中,您正在扩展React。组件类,并且根据ES2015规范,子类构造函数在super()被调用之前不能使用它;此外,如果ES2015类构造函数是子类,则必须调用super()。
class MyComponent extends React.Component {
constructor() {
console.log(this); // Reference Error
}
render() {
return <div>Hello {this.props.name}</div>;
}
}
相比之下:
class MyComponent extends React.Component {
constructor() {
super();
console.log(this); // this logged to console
}
render() {
return <div>Hello {this.props.name}</div>;
}
}
更多细节,根据这个优秀的堆栈溢出的答案
你可能会看到一些通过扩展React创建的组件的例子。不调用super()的组件类,但你会注意到它们没有构造函数,这就是为什么没有必要。
class MyOtherComponent extends React.Component {
render() {
return <div>Hi {this.props.name}</div>;
}
}
我从与我交谈过的一些开发人员那里看到的一个困惑是,那些没有构造函数,因此在任何地方都不调用super()的组件仍然有这个。render()方法中可用的道具。记住,这个规则和这个需要为构造函数创建一个this绑定,只适用于构造函数。
这是我做的小提琴:jsfiddle.net。它表明默认情况下道具不是在构造函数中分配的。据我所知,它们是在方法React.createElement中分配的。因此,super(props)应该只在超类的构造函数手动将props赋给this.props时调用。如果你只是扩展React。组件调用super(props)不会对props做任何事情。也许它会在React的下一个版本中被改变。