は、コンストラクタを持つ場合にのみリアクションコンポーネント内で呼び出されます。例えば、以下のコードは、スーパーは必要ありません。我々はコンストラクタを持っている場合
class App extends React.component {
render(){
return <div>Hello { this.props.world }</div>;
}
}
しかし、その後super()
は必須です:
class App extends React.component {
constructor(){
console.log(this) //Error: 'this' is not allowed before super()
}
}
this
であるためsuper()
がある前にthis
が許可できない理由super()
が呼び出されていない場合は初期化されません。しかし、this
を使用していない場合でも、ES6 class constructors MUST call super if they are subclasses
のため、コンストラクタ内にsuper()
が必要です。したがって、コンストラクタを持っている限り、super()
に電話する必要があります。 (しかし、サブクラスはコンストラクタを持つ必要はありません)。
我々は例えば、this.props
を使用する必要があれば私たちは、コンストラクタ内super(props)
を呼び出す:
class App extends React.component{
constructor(props){
super(props);
console.log(this.props); // prints out whatever is inside props
}
}
私はそれを明確にすることを願ってい。
コンポーネント内のコンストラクタを持つ主な目的は、コンポーネントの初期化直後に何らかのアクションをとることですか? superはあなたに1.)「this」と2へのアクセスを許可します。)それがパラメータとして小道具を取る場合、その親小道具へのアクセス? – stackjlei
スーパーで親コンポーネントの小道具にアクセスできますか? – stackjlei
スーパーの –