[React] 이벤트 파라미터에 따른 함수 사용법

sunaaa·2021년 3월 20일

Q1. 다음의 코드에서 틀린 점을 찾으시오.

handleIdx = () => {
  this.setState({ idx: this.state.idx + 1 })
  console.log(this.state.idx)
}

render() {
  const { data } = this.state
  return(
    <div>
      <span>저의 이름은 {data[idx].name}입니다</span>
      <span>저의 이름은 {data[idx + 1].name}입니다</span>
      <button onClick={() => handleIdx} />
    </div>
  )
}

A. 정답 : <button onClick={() => handleIdx()} />
📛 화살표 함수를 습관적으로 쓰지 말 것
=> <button onClick={handleIdx} /> 라고 쓰면 됨

Q. 그렇다면 어떤 경우에 쓰나?
A. 함수가 실행됐을 때, handleIdx라는 함수에 파라미터로 특정 값이 들어가야 할 때 쓴다. 아무 관련이 없을 때는 줄여서 쓴다.

handleIdx = (idx) => {
  this.setState({ idx: this.state.idx + idx })
  console.log(this.state.idx)
}

render() {
  const { data } = this.state
  return(
    <div>
      <span>저의 이름은 {data[idx].name}입니다</span>
      <span>저의 이름은 {data[idx + 1].name}입니다</span>
      <button onClick={() => handleIdx(1)} />
    </div>
  )
}

Q2. 다음 중 틀린 부분은?

handleIdx = () => {
  this.setState({ idx: this.state.idx + 1 })
  console.log(this.state.idx)
}

render() {
  const { data } = this.state
  return(
    <div>
      <span>저의 이름은 {data[idx].name}입니다</span>
      <span>저의 이름은 {data[idx + 1].name}입니다</span>
      <button onClick={this.handleIdx()} />
    </div>
  )
}

A. <button onClick={this.handleIdx()} />
📛에서 함수 자체가 아닌 함수의 실행 결과를 넘겨줘야함.
<button onClick={this.handleIdx} />로 바뀌어야함.
이벤트와 관계없이 실행되는 함수이기 때문.
onClickhanleIdx의 실행 결과임. setState가 실행되고 render가 실행되고 onClick안에 handleIdx를 부르고 반복.
💎 함수 자체를 넘겨줘야 하는지 함수의 실행 결과를 넘겨줘야 하는지 구분 필요

profile
Be Playful Front-end Developer

0개의 댓글