React에서 제공하는 이벤트는 여러가지 있다.
React Event 종류
Clipboard Event
|
Composition Event
|
Keyboard Event
|
Focus Event
|
Form Event
|
Generic Event
|
Selection Event
|
Touch Event
|
UI Event
|
Wheel Event
|
Image Event
|
Animation Event
|
Transition Event
|
Other Event
|
||
Mouse Event
|
Pointer Event
|
Media Event
|
생각 이상으로 이벤트가 많다. 이것들을 이용해 이벤트에 따른 작업을 할 수 있게 된다.
자세한 내용은 API reference를 참고하기 바란다.
https://reactjs.org/docs/events.html
SyntheticEvent – React
A JavaScript library for building user interfaces
reactjs.org
예제 만들기
이전 글 state에서 onClick을 사용했는데 이번에는 onFocus, onChange를 사용해보겠다.
import React, { useState } from 'react';
const EventEx = () => {
const [textColor, setTextColor] = useState('');
const onChangeTextColor = (e) => setTextColor(e.target.value);
const onBlurTextBox = () => setTextColor("white");
const onFocusTextBox = (e) => {
if(e.target.value === 'white'){
setTextColor('black');
}else{
setTextColor(e.target.value);
}
};
return (
<div>
<input type="text" placeholder='원하는 색을 적어주세요. ex) black, red, yellow' onChange={onChangeTextColor} onBlur={onBlurTextBox} onFocus={onFocusTextBox}></input>
<h1 style={{color:textColor}}>원하는 색입니다.</h1>
</div>
);
};
export default EventEx;
textColor를 state로 갖은 EventEx 컴포넌트를 만들었다.
input 태그는 onChange, onBlur, onFocus 3가지 이벤트를 갖는다.
onChange는 값이 변할때, onBlur는 포커스가 떠날때, onFocus 포커스될 때 마다 해당 함수를 호출한다.
onFocusTextBox 함수
const onFocusTextBox = (e) => {
if(e.target.value === 'white'){
setTextColor('black');
}else{
setTextColor(e.target.value);
}
매개변수로 e를 받는데 이건 자바스크립트 event object로 다양한 속성을 갖는다.
e.target.value는 해당 이벤트를 호출한 요소의 value에 접근해 값을 읽어온 것이다.
앞에서 언급했듯 React.js는 자바스크립트 라이브러리므로 기존 if문을 그대로 사용하면 된다.
event properties and Method
e.preventDefault() | 기존 설정된 이벤트들을 모두 캔슬합니다. |
target | 이벤트가 작동한 해당 요소 |
type | 해당 이벤트 이름 |
timeStamp | 해당 이벤트가 작동된 시간 |
자세한 내용은 아래에서 참고하면 된다.
https://www.w3schools.com/jsref/obj_event.asp
Event Object
W3Schools offers free online tutorials, references and exercises in all the major languages of the web. Covering popular subjects like HTML, CSS, JavaScript, Python, SQL, Java, and many, many more.
www.w3schools.com
'WEB > HTML CSS JS' 카테고리의 다른 글
[React.js] 8. map()을 이용한 컴포넌트 반복 (0) | 2023.01.30 |
---|---|
[React.js] 7. hook useEffect (0) | 2023.01.29 |
[React.js] 5. hook useState (0) | 2023.01.26 |
[React.js] 4. 컴포넌트 component (0) | 2023.01.25 |
[React.js] 3. 요소 element (0) | 2023.01.24 |