1. 程式人生 > >React中constructor(props){}究竟是什麼

React中constructor(props){}究竟是什麼

在React Class中設定state的初始值或者繫結事件時

為什麼需要在 constructor(){} 中加上 super() 呢

我們嘗試去掉 super() 看看編譯的結果:

 
  1. constructor() {

  2. this.state = {searchStr: ''};

  3. this.handleChange = this.handleChange.bind(this);

  4. }

執行這段程式碼時,會發現編譯錯誤:

提示沒有在this之前加上super()

其實就是少了super(),導致了this的 Reference Error

 
  1. class MyComponent extends React.Component {

  2. constructor() {

  3. console.log(this); // Reference Error

  4. }

  5.  
  6. render() {

  7. return <div>Hello {this.props.name}</div>;

  8. }

  9. }

super關鍵字,它指代父類的例項(即父類的this物件)。子類必須在constructor方法中呼叫super方法,否則新建例項時會報錯。這是因為子類沒有自己的this物件,而是繼承父類的this物件,然後對其進行加工。如果不呼叫super方法,子類就得不到this物件。


 

正確的姿勢應該是這樣

 
  1. constructor() {

  2. super();

  3. this.state = {searchStr: ''};

  4. this.handleChange = this.handleChange.bind(this);

  5. }

React的官方例子中都是加上了 props 作為引數

 
  1. constructor(props) {

  2. super(props);

  3. this.state = {searchStr: ''};

  4. this.handleChange = this.handleChange.bind(this);

  5. }

那它們的區別在哪兒呢

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)是完全沒問題的,也建議就直接這樣寫