React中constructor(){}
当你在React class中需要设置state的初始值或者绑定事件时
需要加上constructor(){}
- constructor() {
- this.state = {searchStr: ''};
- this.handleChange = this.handleChange.bind(this);
- }
但当你运行时,是会出现问题的。
提示没有在this之前加上super()
其实就是少了super(),导致了this的 Reference Error
- class MyComponent extends React.Component {
- constructor() {
- console.log(this); // Reference Error
- }
- render() {
- return <div>Hello {this.props.name}</div>;
- }
- }
个人理解super()是继承了整个类的一个引用(希望知道的帮忙解释下)
正确的姿势应该是这样
- constructor() {
- super();
- this.state = {searchStr: ''};
- this.handleChange = this.handleChange.bind(this);
- }
那么React的官方例子中都是加上了props作为参数
- constructor(props) {
- super(props);
- this.state = {searchStr: ''};
- this.handleChange = this.handleChange.bind(this);
- }
那它们的区别在哪儿呢
What's the difference between “super()” and “super(props)” in React when using es6 classes?
借用下stackoverflow上的解释
There is only one reason when one needs to pass props
to super()
:
When you want to access this.props
in
constructor.
(Which is probably redundant since you already have a reference to it.)
只有一个理由需要传递props作为super()的参数,那就是你需要在构造函数内使用this.props
那官方提供学习的例子中都是写成super(props),所以说写成super(props)是完全没问题的,也建议就直接这样写