[React] 이벤트 핸들러

Local Gaji·2023년 6월 3일
0

React

목록 보기
6/18

기존 이벤트 핸들러

  1. 태그 안에 넣는 방식
<button onclick="수행할 내용"></button>

-> 버튼을 클릭하면 내용 실행하기


  1. 자바스크립트
const button = document.getElementById("button")
button.addEventListner(이벤트, 함수)

-> 버튼에 이벤트가 발생하면 함수 실행하기


리액트에서 이벤트 핸들러 사용하기

이벤트명을 카멜 케이스로 (onClick) 작성

const element = (
  <button onClick = {함수1} onMouseOut = {함수2}>
    Press
  </button>
)

리액트 이벤트 핸들러로 검색창 만들기

button에 onClick 이벤트
input에 onChange 이벤트

const root = document.getElementById("root")

const state = {
  keyword: "",
  typing: false,
  result: "",
}

const inputChange = (event) => {
  setState({
    typing: true,
    keyword: event.target.value,
  })
}

const buttonClick = () => {
  setState({
    typing: false,
    result: `The result of ${state.keyword}`,
  })
}

const Search = () => {
  return (
    <>
      <input onChange={inputChange} />
      <button onClick={buttonClick}>search</button>
      <p>
        {state.typing ? `Looking for ${state.keyword}` : state.result}
      </p>
    </>
  )
}

const setState = (newState) => {
  Object.assign(state, newState); // 객체에서 바뀐 부분만 업데이트
  ReactDOM.render(<Search />, root)
}

ReactDOM.render(<Search />, root)

변경 사항이 있을때마다 state 객체를 업데이트하고 render를 진행
입력중일 때는 keyword, 버튼을 클릭했을 때는 result를 표시

0개의 댓글