[TIL] React 기초 - 컴포넌트, 이벤트 핸들링 (21.01.22)

12826 단어 ReactTILReact

기초 지식

JS

화살표 함수

  • ES6에 추가된 함수 표현 방식
  • 기존 function과 사용 용도가 조금 다름
  • function()에서 this는 자신이 종속된 객체를 가리킴
  • 화살표 함수에서 this는 자신이 종속된 인스턴스를 가리킴

🧩 컴포넌트

props

기초

  • 컴포넌트 속성 설정 시 사용하는 요소
  • 부모 컴포넌트에서만 설정 가능 (읽기 전용)
  • this를 이용해 불러올 수 있음
//MyComponent.js
...
return (
  <div>
    제 이름은, {this.props.name}입니다.
  </div>
)
...
---------------------------------------
//App.js
...
return (
	<MyComponent name="React"/>
)

defaultProps

  • 부모 컴포넌트에서 props 값 지정하지 않았을 경우 기본 값으로 설정
// 전통적 방법
...
class MyComponent extends Component {
  ...
}

MyComponent.defaultProps = {
  name: '기본 이름'
} //클래스 외부에 선언
...
---------------------------------------
// transform-class-properties 문법
...
class MyComponent extends Component {
  static defaultProps = {
    name: '기본이름'
} //클래스 내부에 선언
...

propTypes

  • props 타입 지정 / 필수 props 지정
// 전통적 방법
...
class MyComponent extends Component {
  ...
}

MyComponent.propTypes = {
  name: PropTypes.string
} //클래스 외부에 선언
...
---------------------------------------
// transform-class-properties 문법
...
class MyComponent extends Component {
  static propTypes = {
    name: PropTypes.string
    age: PropTypes.number.isRequired // 필수 props 지정
} //클래스 내부에 선언
...

state

기초

  • 컴포넌트 내부에서 읽고 업데이트할 수 있는 값 지정
  • 초기화 필수
  • this.setState() 메서드만을 이용하여 값 업데이트

초기화

생성자 메서드

  • 생성자 메서드는 컴포넌트를 새로 만들 때 실행됨.
  • rcc(react component class)는 리액트의 Component 클래스를 상속함
  • constructor 메서드를 따로 만들지 않으면 Component 클래스의 생성자 메서드 그대로 사용
  • 직접 constructor 메서드를 작성하여 추가 작업을 하려면, Component 클래스의 constructor 메소드 먼저 호출해야함.
...
constructor(props) {
  super(props); // Component 클래스의 constructor 메서드 호출
}
  • state 초기화는 constructor 메서드 내부에서 설정
// 전통적 방식
constructor(props) {
  super(props);
  this.state = {
    number: 0
  }
}
---------------------------------------
// transform-class-properties 문법
...
class MyComponent extends Component {
  state = {
    number: 0
  }
...

렌더링

...
<div>
  <p>{this.state.number}</p>
</div>

업데이트

  • setState로 업데이트 해야만 자동으로 리렌더링 됨 (트리거 역할)
  • this.forceUpdate() 메서드를 호출하여 강제 리렌더링 할 수 있으나 매우 비효율적
...
<button onClick={() => {
  this.setState({
    number: this.state.number + 1
  }) // 업데이트
}}>

⌨️ 이벤트 핸들링

기초

주의사항

  1. 이벤트 이름은 camelCase
  2. 이벤트에 자바스크립트 코드 전달(x) -> 함수형태의 객체 전달
  3. DOM요소에만 이벤트 설정 가능 -> 컴포넌트 자체에 이벤트 설정 불가

좋은 웹페이지 즐겨찾기