React - Constructor와 Super

정태수·2023년 9월 7일
0

React

목록 보기
1/3
post-thumbnail

Constructor(), 한글로는 생성자라 불리는 함수는 state(컴포넌트의 상태) 값을 초기화 하거나 메서드를 바인딩 할 때 사용한다

super()는 자식 클래스가 생성될 때 부모 클래스의 생성자를 참조하는 방법

React 버전에 따라 super(props) 대신 super()를 사용하는 것이 허용될 수도 있으며, 최신 버전의 React에서는 super(props) 대신 super()를 사용해도 props가 자동으로 전달됩니다.

super(props)를 쓰는 이유
생성자 호출 이후에 props 를 super에 할당하지 않는경우에는 this.props를 불럿을때 undefined가 뜨지만 할당을 한 경우에는 아래 코드와 같이 props에 대한 값이 출력됩니다.

super() 전에 this가 허용되지 않는 이유는, super()가 불리지 않으면 this가 초기화되지 않기 때문입니다

class Button extends React.Component {
  constructor(props) {
    super(props); // super에 props 할당
    console.log(props);  // ✅ {}
    console.log(this.props); // ✅ {}
  }
  // ...
}

이렇게 super(props) 를 호출하는 것은 생성자 내부에서도 this.props 를 정상적으로 사용할 수 있도록 보장해 줍니다.

constructor 안에서 this.props에 접근하고 싶을 때만 super(props)를 부르세요. 다른곳에서 접근 시, React가 자동으로 설정한다.

class MyComponent extends Component {
  constructor(props) {
    super(props);
  }

  handleClick() {
    // 이 메서드 내에서 'this'가 어떤 객체를 참조할까요?
    console.log('Button clicked', this.props.someProp);
  }

  render() {
    return (
      <button onClick={this.handleClick}>Click Me</button>
    );
  }
}

위 코드에서는 컴포넌트를 가리키고 있지 않다. 따라서 this.props 에 접근x

class MyComponent extends Component {
  constructor(props) {
    super(props);
    
    // 메서드 바인딩
    this.handleClick = this.handleClick.bind(this);
  }

  handleClick() {
    // 이제 'this'는 올바른 컴포넌트 인스턴스를 참조합니다.
    console.log('Button clicked', this.props.someProp);
  }

  render() {
    return (
      <button onClick={this.handleClick}>Click Me</button>
    );
  }
}
profile
프론트엔드 개발자

0개의 댓글