定義class組件,為什么需要加上 super() ?
- 我們嘗試去掉 super() 看看編譯的結果:
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>; } }
2.那super的作用究竟是什么?
super關鍵字,它指代父類的實例(即父類的this對象)。
子類必須在constructor方法中調用super方法,否則新建實例時會報錯。
這是因為子類沒有自己的this對象,而是繼承父類的this對象,然后對其進行加工。
如果不調用super方法,子類就得不到this對象。
3.正確的姿勢
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); }
4.加與不加props的區別究竟在哪里呢?
React中constructor(props){}究竟是什么,以及super(props)與super() 它們的區別在哪兒呢?
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