이벤트 핸들링

김상현·2020년 6월 19일
0

React

목록 보기
5/16

이벤트처리하기

  • React에서는 false를 반환해도 기본 동작을 방지할 수 없다. 반드시 preventDefault를 명시적으로 호출해야한다.
  • DOM 엘리먼트가 생성된 후 리스너를 추가하기 위해 addEventListener를 호출할 필요가 없다. 대신, 엘리먼트가 처음 렌더링될 때 리스너를 제공하면 된다.
const ActionLink = () => {
  const handleClick = (e) => {
    e.preventDefault();
    console.log("hi");
  }
  
  return(
    <a href="#" onClick={handleClick}>
      Click me
    </a>
  )
}

  • 이벤트 메서드를 바인딩하지 않으면 this가 window객체를 바라보게된다. 바인딩 혹은 화살표함수를 사용해야된다.
class Toggle extends React.Component {
  constructor(props) {
    super(props);
    this.state = {isToggleOn: true};

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

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


조건부 렌더링


  • 컴포넌트가 렌더링하는 것을 막고싶을 때는 렌더링 결과를 출력하는 대신 null을 반환하면 해결할 수 있다.
const WarningBanner({warn}) {
  if (!warn) {
    return null;
  }

  return (
    <div className="warning">
      Warning!
    </div>
  );
  
class App extends React.Component {
  constructor(props){
  super(props);
  this.state = {warn: true};
  }
  
  render(){
    return (
      <WraningBanner warn={this.state.warn}/>
    )
  }
}


리스트와 key


  • 여러개의 컴포넌트를 반환하기 위해 map()함수를 이용하여 배열을 반복 실행합니다.
  • 엘리먼트에 안정적인 고유성을 부여하기 위해 배열 내부에 key 값을 지정해야한다.
const numbers = [1, 2, 3, 4, 5];
const listItems = numbers.map((number) =>
  <li key={number.id}>
    {number}
  </li>
);
  • key는 형제 사이에서 고유한 값이어야하고 key 값으로 배열의 인덱스를 사용하는 것은 권장하지 않는다. 배열의 순서가 바뀔 수도 있기 때문이다.(filter)

0개의 댓글