React
eventHandle로 DropDown 만들기
Doityoo
2022. 11. 28. 16:44
import React, {useState} from 'react';
import "./styles.css";
export default function App() {
const [choice, setChoice] = useState();
const fruits = ["apple", "grape", "watermelon", "carrot", "orange"];
const options = fruits.map((fruit) => {
return <option value={fruit}>{fruit}</option>
})
const handleFruit = (e) => {
setChoice(e.target.value);
}
return (
<div className="App">
<select value={choice} onChange={handleFruit}>
{options}
</select>
<h1>You choose "{choice}"</h1>
</div>
);
}
- JSX를 사용하여 문자열이 아닌 함수로 이벤트 처리 함수(이벤트 핸들러)를 전달한다.
- HTML의 이벤트 처리 방식
<button onclick="handleEvent()">Event</button>
- react의 이벤트 처리 방식
<button onClick={handleEvent}>Event</button>
react에서 이벤트는 중괄호를 사용한다.
그리고 함수를 실행하는 ()를 붙이면 안된다!
<button onClick={handleEvent()}>Event</button>
// 컴포넌트가 렌더링될 때 함수가 실행되어 undefined
onClick 이벤트에 함수()를 바로 호출하면 컴포넌트가 렌더링 될 때 함수 자체가 아닌 함수 호출의 결과가 onClick에 적용된다.
때문에 버튼을 클릭할 때가 아닌, 컴포넌트가 렌더링 될 때에 함수가 실행되고 따라서 그 결과인 undefined가 뜬다.
(함수는 리턴 값이 없을 때 undefined 를 반환)
그렇기에 함수만 써주거나,화살표 함수를 정의해줘서 해당 컴포넌트가 state에 접근할수 있도록 해준다.
// 1.
const handleEvent = () => {...}
<button onClick={handleEvent}>Event</button>
// 2.
<button onClick={()=>{ ... }}>Event</button>