anott
기록
anott
  • 분류 전체보기
    • 오라클
    • SQL
    • 알고리즘
      • 백준저지
      • 프로그래머스
      • SWEA
    • 개발 관련
    • 프론트엔드
      • TypeScript, Next.js
      • React 공식문서 읽기
hELLO · Designed By 정상우.
anott

기록

프론트엔드/React 공식문서 읽기

이벤트 처리하기

2022. 5. 26. 23:57
https://ko.reactjs.org/docs/handling-events.html를 읽고 정리한 글입니다.

 

  • React의 이벤트는 camelCase 사용
  • preventDefault를 사용해서 기본 동작을 방지
    • e는 합성 이벤트이며, React는 W3C 명세에 따라 합성 이벤트를 정의하므로 브라우저 호환성에 대해 걱정할 필요 없다
  • JavaScript에서 클래스 메서드는 기본적으로 바인딩되어 있지 않다
    • 방법 3의 문제점은 LoggingButton이 렌더링될 때마다 다른 콜백이 생성된다는 것
      • 콜백이 하위 컴포넌트에 props로 전달된다면 그 컴포넌트들이 추가로 다시 렌더링 수행 가능
// 방법 1
class Toggle extends React.Component {
  constructor(props) {
    super(props);
    this.state = {isToggleOn: true};

    // 콜백에서 `this`가 작동하려면 아래와 같이 바인딩 해주어야 합니다.
    this.handleClick = this.handleClick.bind(this);
  }

  handleClick() {
    this.setState(prevState => ({
      isToggleOn: !prevState.isToggleOn
    }));
  }

  render() {
    return (
      <button onClick={this.handleClick}>
        {this.state.isToggleOn ? 'ON' : 'OFF'}
      </button>
    );
  }
}

ReactDOM.render(
  <Toggle />,
  document.getElementById('root')
);



// 방법 2
class LoggingButton extends React.Component {
  // 이 문법은 `this`가 handleClick 내에서 바인딩되도록 합니다.
  // 주의: 이 문법은 *실험적인* 문법입니다.
  handleClick = () => {
    console.log('this is:', this);
  }

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



// 방법 3
class LoggingButton extends React.Component {
  handleClick() {
    console.log('this is:', this);
  }

  render() {
    // 이 문법은 `this`가 handleClick 내에서 바인딩되도록 합니다.
    return (
      <button onClick={() => this.handleClick()}>
        Click me
      </button>
    );
  }
}
  • 이벤트 핸들러에 인자 전달하는 두 가지 방법
// 방법 1 (화살표 함수)
<button onClick={(e) => this.deleteRow(id, e)}>Delete Row</button>

// 방법 2 (Function.prototype.bind 사용)
<button onClick={this.deleteRow.bind(this, id)}>Delete Row</button>

 

저작자표시 비영리 (새창열림)

'프론트엔드 > React 공식문서 읽기' 카테고리의 다른 글

리스트와 Key  (0) 2022.05.30
조건부 렌더링  (0) 2022.05.28
State and Lifecycle  (0) 2022.05.25
Components와 Props  (0) 2022.05.24
Rendering Elements (엘리먼트 렌더링)  (0) 2022.05.23
    '프론트엔드/React 공식문서 읽기' 카테고리의 다른 글
    • 리스트와 Key
    • 조건부 렌더링
    • State and Lifecycle
    • Components와 Props
    anott
    anott

    티스토리툴바