React 컨스트럭터에서 super()를 호출하는 기능은 무엇입니까?
Learning React는 문서로부터 다음 예를 제시합니다.
class Square extends React.Component {
constructor() {
super();
this.state = {
value: null,
};
}
...
}
Mozilla에 따르면 Super를 사용하면this컨스트럭터 안에 있습니다.스탠드아론을 사용해야 하는 다른 이유가 있습니까?super(알고 있습니다.super부모 클래스의 메서드에도 액세스 할 수 있습니다). 단, React를 사용하면 호출만 하는 다른 사용 사례가 있습니까?super()혼자서요?
super()를 호출합니다.constructor그것의parentclass. 부모 클래스에서 일부 변수에 액세스해야 할 때 필요합니다.
리액트에서는 전화할 때super리액트는 소품만 있으면props를 통해 컴포넌트 전체에서 이용 가능this.props아래 예 2를 참조해 주세요.
없이.super()
class A {
constructor() {
this.a = 'hello'
}
}
class B extends A {
constructor(){
console.log(this.a) //throws an error
}
}
console.log(new B())
와 함께super()
class A {
constructor(props) {
this.props = props
}
}
class B extends A {
constructor(props) {
super(props)
console.log(this.props)
}
}
console.log(new B({title: 'hello world'}))
super()생성자가 있는 경우에만 반응 성분 내부에서 호출됩니다.예를 들어, 아래 코드는 슈퍼를 필요로 하지 않습니다.
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필요한 건super()건설자 내부가 그 이유는ES6 class constructors MUST call super if they are subclasses그래서 전화하셔야 합니다.super()생성자가 있으면 됩니다(단, 하위 클래스에 생성자가 있을 필요는 없습니다).
전화드립니다super(props)컨스트럭터 내부에서는this.props예를 들어 다음과 같습니다.
class App extends React.component{
constructor(props){
super(props);
console.log(this.props); // prints out whatever is inside props
}
}
확실히 할 수 있었으면 좋겠어요.
추가할 가치가 있다super()superclass contractor의 줄임말로 상속의 개념입니다.
디폴트로는 클래스Square슈퍼클래스에서 컨스트럭터를 상속하다React.Component.
상속된 생성자는 새 생성자를 선언하여 재정의할 수 있습니다.constructor()방법.
슈퍼클래스 컨스트럭터를 덮어쓰지 않고 확장하려는 경우 다음 명령을 사용하여 명시적으로 호출해야 합니다.super().
의 컨스트럭터를 실장하는 경우React.Component subclass, 당신이 전화해야 합니다.super(props)다른 어떤 진술보다 먼저요그렇지않으면,this.props될 것이다undefined버그로 이어질 수 있습니다.
JavaScript에서 super는 상위 클래스 생성자를 나타냅니다.
중요한 것은 상위 생성자를 호출할 때까지 생성자에서 이 기능을 사용할 수 없다는 것입니다.JavaScript에서 허용되지 않음: 그러나 super() 호출이 this.name을 설정하기 전에 함수가 호출되었는지 여부를 잊어버렸습니다.this.name은 아직 정의되지 않았습니다.보시다시피, 이런 코드는 생각하기 매우 어렵습니다.이러한 함정을 피하기 위해 JavaScript는 컨스트럭터에서 이 함정을 사용하려면 먼저 super를 호출해야 합니다.부모가 알아서 하게 놔둬!이 제한은 클래스로 정의된 React 컴포넌트에도 적용됩니다.
super();는 리액트에 의해 필수는 아니지만 ES6 서브클래스에 의해 필수가 됩니다.
「」를 this는 ' 때마침.super ?? ??왜?super를 부를 때 합니다.constructor.
왜 하죠?constructor은 '값을하면 됩니다.this키워드를 지정합니다.
언급URL : https://stackoverflow.com/questions/40433463/what-does-calling-super-in-a-react-constructor-do
'source' 카테고리의 다른 글
| javascript scrollIntoView를 부드럽게 만드는 방법 (0) | 2023.03.02 |
|---|---|
| Angularjs는 베스트 프랙티스를 최소화합니다. (0) | 2023.03.02 |
| JDBC ResultSet: getDateTime이 필요한데 getDate와 getTimeStamp만 있습니다. (0) | 2023.02.25 |
| 변경 사항 없이 이 페이지에 액세스할 수 있는 권한이 없습니다. (0) | 2023.02.25 |
| Ajax 호출 후 Django 템플릿을 사용한JSON 오브젝트 렌더링 (0) | 2023.02.25 |