我正在尝试学习React。
React文档中说要按以下方式传递构造函数参数。
class Clock extends React.Component {
constructor(props) {
super(props);
this.state = {date: new Date()};
}
render() {
这篇文章称,在该函数中引用 super 的原因是,如果您想在构造函数中访问 this.props,则可能需要在super()中具有props。
但是 - 如果您不需要这样做,只需要初始化状态,您是否仍然需要 super() 语句?
我看过很多教程,它们将其定义为以下内容:
class Basic extends React.Component {
state = {
selectedValue: null,
createdAt: null
};
我找不到为什么这是可以接受的的参考资料。即使构造函数不需要props,你是否还需要super?
props
(this.props),那么您就不需要编写super(props)
。这是不必要的。 - Ryan Nghiem