天天看點

React中constructor及super

constructor( )

React

constructor

表示父類的構造方法,用來建立父類的this對象,這是

ES6

對類的預設方法,該方法是類中必須有的,如果沒有顯示定義,則會預設添加空的

constructor( )

方法。

class Point {
}

// 相當于
class Point {
  constructor() {}
}
           

super( )

class

方法中,繼承使用

extends

關鍵字來實作。子類必須在

constructor( )

調用 super( )方法,否則建立執行個體時會報錯,因為子類沒有自己的this對象,而是繼承父類的

this

對象,然後對其進行加工,如果不調用super方法;子類就得不到this對象。

有super時:

React中constructor及super

無super時:

React中constructor及super

很明顯自動就報錯了,是以隻要有

constructor

就必須有

super

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>
           

那麼報錯如下:

React中constructor及super

當把

App

元件中的

constructor

改為:

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

那麼運作顯示正确

是以說

super()

super(props)

的差別就是你是否需要在構造函數内使用

this.props

,如果需要那麼你就必須要寫

props

,如果不需要,那麼寫不寫效果是一樣的

轉載至https://www.jianshu.com/p/1b5e86c68458