Back to the Basics

[React]React Event Handling 본문

Web/React

[React]React Event Handling

9Jaeng 2021. 8. 20. 15:02
728x90
반응형

공식 홈페이지도 참고해보자!

React 방식과 DOM 방식 차이

React Event Handling은 DOM의 처리 방식과 비슷하지만 몇 가지 차이점이 있다.

  1. 문법적인 차이는 공식 홈페이지에서도 나와있듯이
  • React에서 Event는 camelCase로 사용한다
  • JSX를 사용하여 "함수"로 Event Handler(이벤트 처리 함수)를 전달한다.

예를 들면 아래의 코드와 같다.

{/* HTML */}
<button conclick="handleEvent()">Click me</button>

{/* React */}
<button onClick={handleEvent}Click me</button>
  1. 명시적으로 preventDefault를 호출해야 한다.

DOM에서는 아래와 같이 false를 return 하여 기본 동작을 방지할 수 있지만, React는 false를 반환해도 방지할 수 없으므로 반드시 preventDefault를 호출해야 한다.

{/* return false를 통해 기본적으로 정의된 이벤트를 작동하지 못하게 한다 */}
<form onsubmit="console.log('You clicked submit/'); return false">
  <button type="submit">Submit</button>
</form>

{/* 물론 DOM에서도 event.preventDefault()를 사용할 수 있다*/}
<a hfer="sora9z.tistory.com" id="link">sora9z의 티스토리 블로그로 이동</a>
<script>
  document.querySelector('#link').addEventListener('click',function(e){
  e.preventDefault();
});

// a tag를 클릭 시 링크값이 있어도 이동하지 않는다
</script>

자주 사용되는 이벤트 처리들

1. onChange

  • input , textarea , select tag와 같은 form(폼) 엘리먼트는 사용자의 입력값을 제어하는 데 사용된다 (변경될 수 있는 값)
  • --> React는 이러한 값을 컴포넌트의 State로 관리하고 업데이트한다.
  • Onchange는 input의 text가 바뀔 때마다 발생하는 이벤트이다
  • onChange Event가 발생하면 e.target.value를 통해 이벤트 객체에 담겨 있는 input값을 읽어올 수 있다.
  • 이벤트가 발생하면 이벤트 객체에 담긴 input 값을 갱신 함수를 통해 새로운 state로 업데이트한다.

2. onClick

onClick event는 사용자가 "클릭"이라는 행동을 했을 때 발생하는 이벤트이며, a 및 button 태그를 통한 링크 이동과 같이 주로 사용자 행동에 따라 반응해야 할 경우 자주 사용하는 이벤트이다.
onClick 시 실행되는 함수를 줄 때, 함수 호출 문이 아닌 함수 자체를 전달해야 한다. 만약 onClick={alert(name)} 와 같이 함수를 호출해버리면 함수의 호출 결과가 적용이 되고 버튼을 클릭할 때가 아닌, 컴포넌트가 렌더링 될 때에 alert가 실행이 되고 return 값이 없으므로 ubdefinded를 반환하게 된다. 아무런 결과도 일어나지 않는다.

함수를 전달하는 방법으로는 함수를 직접 정의하는 방법과 함구 자체를 전달하는 방법이 있다.

{/*함수를 직접 정의*/}
return (
  <button onClick={()=>alert(name)}>Button</button>
);

{/*함수 자체를 전달*/}
return (
  <button onClick={handleClick}>Button</button>

위의 두 경우 모두 arrowa 함수를 사용해서 함수를 정의해야 해당 컴포넌트가 가진 state에 함수들이 접근할 수 있다.

onClick과 onChange code 예시

function NameFrom(){
  const [name,setname]=useState("");

  const handleChange=(e)=>{
    setname(e.target.value);
  };

  const handleClick=(e)=>{
    alert(name);
  }

  return (
    <div className="App">
      <h1>Event handler practice !!</h1>
      <input type="text" value={name} onChange={handleChange}></input>
      <button onClick={handleClick}>Click me me</button>
      <h3>{"Kang "}{name}</h3>
    </div>
  );
}

select tag 사용

select tag는 사용자가 드롭다운 목록을 열어 그중 한 가지 옵션을 선택하고 그 옵션이 state 변수에 갱신되게 된다.

const SelectExample=()=>{
  const [choice,setChoice]=useState("apple");

  const fruits=["apple","orange","pineapple","strawberry","grape"];
  const options=fruits.map((fruit)=>{
    return <option value={fruit}>{fruit}</option>

  });

  const handleFruit=(event)=>{
    setChoice(event.target.value)
  }

  return(
    <div className="App">
      <select value={choice} onChange={handleFruit}>
        {options}
      </select>
    </div>
  )
}

const option은 map을 사용하여 옵션 엘리먼트를 return 하도록 하였고, select 태그의 option으로 사용하였다.
handleFruite 함수는 event가 발생하면 event.targer.value로 setChoice 함수를 통해 state를 업데이트한다.
마지막 return 문 select 태그에서 onChange (이벤트가 발생하면) handleFruit를 호출한다.

pop up 사용

Pop Up은 open과 close를 state를 통해 관리할 수 있다.

const PopupExample=()=>{
  const [showPop,setShowPop]=useState(false);

  const togglePopup=()=>{
    setShowPop(!showPop)

  }

  return (
    <div className="App">
      <h1>Fix me to open Pop Up</h1>
      <button className="open" onClick={togglePopup}>Click and Open me</button>
      {showPop ? (
        <div className="popup">
          <div classname="popup_inner">
            <h2>Success!!!</h2>
            <button className="close" onClick={togglePopup}>
              Click and Close me
            </button>
          </div>
        </div>
      ) : null}
    </div>
  )
}

className이 open인 button을 누르면 onClick 이벤트가 발생하고 togglePopup 함수를 호출한다.
togglePopup함수는 setShowPop을 호출하고! showPop을 인자로 주어 state를 갱신한다.

삼항 연산자를 사용하여 showPop이 true이면 className이 "popup"인 DOM element가 실행이 되어 className이 "close"인 button과 Success!! 메시지가 pop up이 된다.

close button을 누르면 togglePopup 함수가 실행이 되고 state는 false로 갱신이 된다.
다시 삼항 연산자를 통해 null 값이 되어 pop up이 사라진다.

728x90
반응형
Comments