constructor()

2018-09-19  本文已影响0人  16manman

constructor里的this.state和直接写this.state区别?
答案:没有区别

在React中constructor表示父类的构造方法,用来新建父类的this对象,这是ES6对类的默认方法,该方法是类中必须有的,如果没有显示定义,则会默认添加空的constructor( )方法。

class Point {
}

// 相当于
class Point {
  constructor() {}
}
super( )

class方法中,继承使用 extends 关键字来实现。子类 必须 在 constructor( )调用 super( )方法,否则新建实例时会报错,因为子类没有自己的this对象,而是继承父类的this对象,然后对其进行加工,如果不调用super方法;子类就得不到this对象。

super or super(props)

先看个例子:

class Main extends React.Component {
    constructor() {
        super();
        this.state = {count: 1};
    }

    render() {
        return (
            <div>
                {this.state.count}
                <App count={this.state.count}/>
            </div>
        );
    }
}

class App extends React.Component {
    constructor() { //没有写props
        super();
    }

    render() {
        return (
            <div>
                {this.props.count}
            </div>
        );
    }
}

运行后显示正确,当在constructor和super中写了props,也毫无影响,运行显示正确,那么将App组件中的constructor改为:

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

显示部分改为:

<div>
       {this.state.c}
</div>

那么则会报错

当把App组件中的constructor改为:

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

那么运行显示正确

所以说super()和super(props)的区别就是你是否需要在构造函数内使用this.props,如果需要那么你就必须要写props,如果不需要,那么写不写效果是一样的

参考链接:https://www.jianshu.com/p/1b5e86c68458

待研究:https://www.jianshu.com/p/26c63a17e362

constructor作用:

1.初始化state
2.bind this

constructor(props) {
    super(props);
    this.handleChange = this.handleChange.bind(this);
    this.state = {temperature: ''};
  }

其实也可以被完全替代

class Counter extends Component {
      state = { counter: this.props.initCount };
      render() {
          return <button onClick={this.onIncrementClick}>{this.state.counter}</button>;
    }}
class Counter extends Component {
  state = { counter: 0 };
  onIncrementClick = () => {
    this.setState(this.increment);
  }
  increment(state) {
     return { ...state, counter: state.counter + 1 };
  }
render() {
  return <button onClick={this.onIncrementClick}>{this.state.counter}</button>; 
 }
}

参考地址: https://www.jianshu.com/p/094a1c813f80

constructor(props) {
  super(props);
  this.state = {
    color: props.initialColor
  };
}
上一篇下一篇

猜你喜欢

热点阅读