react class 的 constructor方法为什么要带props

class Clock extends React.Component {
  constructor(props) {
    super(props);
    this.state = {date: new Date()};
  }

这里的props是什么意思,是内置的对象吗?看到这种写法很疑惑。

阅读 3.2k
1 个回答

props就是传递给你组件的props。在constructor中,如果不需要取props中的值,是可以简写的。

constructor() {
  super();
}

写出来,一般是想给组件设置初始化的state。如:

constructor(props) {
  super();
  this.state = {
    xxx: props.xxx
  }
}

// 然后再配合componentWillReceivePorps来实现props和state同步的目的
componentWillReceiveProps(np) {
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题