GitHub - gilbutITbook/080203: 리액트를 다루는 기술 개정판
리액트를 다루는 기술 개정판. Contribute to gilbutITbook/080203 development by creating an account on GitHub.
github.com
(본 포스팅은 위의 리액트를 다루는 기술(개정판)을 기반으로 작성했습니다.)
'리액트의 이벤트 시스템'
const Say = () => {
const [message, setMessage] = useState("");
const onClickEnter = () => setMessage("안녕하세요");
const onClickLeave = () => setMessage("안녕히 가세요!");
const [color, setColor] = useState("black");
return (
<div>
<button onClick={onClickEnter}>입장</button>
<button onClick={onClickLeave}>퇴장</button>
(HTML 이벤트와 인터페이스가 동일)
이벤트 : 사용자가 웹 브라우저에서 DOM 요소들과 상호 작용하는 것
이벤트 핸들러 : 이벤트를 처리하는 것
이벤트를 사용할 때 주의 사항 ?
1. 이벤트 이름은 카멜 표기법으로 작성합니다.
2. 이벤트에 실행할 자바스크립트 코드를 전달하는 것이 아니라, 함수 형태의 값을 전달합니다.
3. DOM 요소에만 이벤트를 설정할 수 있습니다.
div, button, input, form, span 등의 DOM 요소에는 이벤트를 설정할 수 있지만, 직접 만든 리액트 컴포넌트에는 이벤트를 자체적으로 설정할 수 없다.
<MyComponent onClick={doSomething} />
이 코드는 이름이 onClick 인 props 를 컴포넌트에 전달할 뿐이다.
컴포넌트에 자체적으로 이벤트를 설정할 수는 없지만, 전달받은 props 를 컴포넌트내부의 DOM 이벤트로 설정할 수는 있다.
<div onClick={this.props.onClick}>{/* ... */}</div>
'클래스형 컴포넌트'
import React, {Component} from 'react';
class EventPractice extends Component {
state = {
username: '',
message: '',
};
handleChange = (e) => {
this.setState({
[e.target.name]: e.target.value,
});
};
handleClick = () => {
alert(this.state.username + ': ' + this.state.message);
this.setState({
username: '',
message: '',
});
};
render() {
return (
<div>
<h1>Event Practice</h1>
<input
type="text"
name="username"
placeholder="User name"
value={this.state.username}
onChange={this.handleChange}
/>
<input
type="text"
name="message"
placeholder="type something"
value={this.state.message}
onChange={this.handleChange}
/>
<button onClick={this.handleClick}>Submit</button>
</div>
);
}
}
export default EventPractice;

- EventPractice 컴포넌트에 input 요소를 렌더링하는 코드와 해당 요소에 onChange 이벤트 설정
- e 객체는 SyntheticEvent로 웹 브라우저의 네이티브 이벤트를 감싸는 객체
- SyntheticEvent는 네이티브 이벤트와 달리 이벤트가 끝나고 나면 이벤트가 초기화되므로 정보를 참조할 수 없음
- 만약 비동기적으로 이벤트 객체를 참조할 일이 있다면 e.persist() 함수를 호출해야 함
- 함수를 미리 준비하여 전달하는 방법 → 가독성이 더욱 높음
- constructor 함수에서 함수를 바인딩하는 작업이 이루어짐
- input이 여러 개일 때는 event 객체를 활용하는 것이 쉽게 처리할 수 있음
- onChange 이벤트 핸들러에서 e.target.name은 해당 input의 name을 가르킴
handleChange = (e) => {
this.setState({
[e.target.name]: e.target.value,
});
};
- e.target.name을 [ ]로 감싸는데, 이렇게 객체 안에서 key를 [ ]로 감싸면 그 안에 넣은 레퍼런스가 가르키는 실제 값이 key 값으로 사용됨
'함수형 컴포넌트'
import React, { useState } from "react";
const EventPractice = (props) => {
const [username, setUsername] = useState("");
const [message, setMessage] = useState("");
const onChangeUsername = (e) => setUsername(e.target.value);
const onChangeMessage = (e) => setMessage(e.target.value);
const onClick = () => {
alert(username + ": " + message);
setUsername("");
setMessage("");
};
const onKeyPress = (e) => {
if (e.key === "Enter") {
onClick();
}
};
return (
<>
<h1>이벤트연습</h1>
<input
type="text"
name="messge"
placeholder="아무거나 입력"
value={username}
onChange={onChangeUsername}
></input>
<input
type="text"
name="messge"
placeholder="아무거나 입력"
value={message}
onChange={onChangeMessage}
onKeyPress={onkeypress}
></input>
<button onClick={onClick}>확인</button>
</>
);
};
export default EventPractice;
- e.target.name을 활용하지 않고 onChange 관련 함수 두 개를 따로 만들어줌
- 인풋의 개수가 많아질 것 같다면 e.target.name을 활용하는게 더 좋을 수도 있음
import React, {useState} from 'react';
const EventPractice = (props) => {
const [form, setForm] = useState({
username: "",
message: ""
});
const { username, message } = form;
const onChange = (e) => {
const nextForm = {
...form, // 기존의 form 내용을 이 자리에 복사한 뒤
[e.target.name]: e.target.value // 원하는 값을 덮어 씌우기
};
setForm(nextForm);
};
const onClick = () => {
alert(username + ": " + message);
setForm({
username: "",
message: ""
});
};
const onKeyPress = (e) => {
if (e.key === "Enter") {
onClick();
}
};
return (
<>
<h1>이벤트연습</h1>
<input
type="text"
name="messge"
placeholder="아무거나 입력"
value={username}
onChange={onChange}
></input>
<input
type="text"
name="messge"
placeholder="아무거나 입력"
value={message}
onChange={onChange}
onKeyPress={onKeyPress}
></input>
<button onClick={onClick}>확인</button>
</>
);
};
export default EventPractice;
- useState를 통해 사용하는 상태에 문자열이 아닌 객체를 넣음
- e.target.name 값을 활용하려면, useState를 쓸 때 인풋 값들이 들어 있는 form 객체를 사용해주면 됨
'결론 및 정리'
클래스형 컴포넌트 vs 함수형 컴포넌트
클래스 컴포넌트는 라이프 사이클 기능 및 state 관리 기능을 사용할 수 있으며, 임의 메서드를 정의할 수 있다.
함수형 컴포넌트는 hook을 통해 라이프 사이클 기능과 state 관리 기능 코드를 짤 수 있으며, 클래스형 컴포넌트보다 선언하기 더 편하고, 메모리 자원을 덜 사용한다는 장점이 있다. 또한, 사이클 API를 사용할 수 없다는 단점이 있었지만, hook이 도입되면서 해결되었다.
- 리액트에서 이벤트를 다루는 것을 순수 자바스크립트 또는 iQuery를 사용한 웹 애플리케이션에서 이벤트를 다루는 것과 비슷하다.
- 기존 HTML DOM Event를 알고 있다면 리액트의 컴포넌트 이벤트도 쉽게 따를 수 있다.
- 8장의 useReducer와 Hooks를 사용하면 더 편하게 만들 수 있다.
'React' 카테고리의 다른 글
6# 컴포넌트 반복 (0) | 2023.01.27 |
---|---|
5# ref: DOM에 이름 달기 (0) | 2023.01.13 |
3# 컴포넌트 (0) | 2022.12.30 |
2# JSX (0) | 2022.12.23 |
1# 리액트 시작 (0) | 2022.12.23 |
GitHub - gilbutITbook/080203: 리액트를 다루는 기술 개정판
리액트를 다루는 기술 개정판. Contribute to gilbutITbook/080203 development by creating an account on GitHub.
github.com
(본 포스팅은 위의 리액트를 다루는 기술(개정판)을 기반으로 작성했습니다.)
'리액트의 이벤트 시스템'
const Say = () => {
const [message, setMessage] = useState("");
const onClickEnter = () => setMessage("안녕하세요");
const onClickLeave = () => setMessage("안녕히 가세요!");
const [color, setColor] = useState("black");
return (
<div>
<button onClick={onClickEnter}>입장</button>
<button onClick={onClickLeave}>퇴장</button>
(HTML 이벤트와 인터페이스가 동일)
이벤트 : 사용자가 웹 브라우저에서 DOM 요소들과 상호 작용하는 것
이벤트 핸들러 : 이벤트를 처리하는 것
이벤트를 사용할 때 주의 사항 ?
1. 이벤트 이름은 카멜 표기법으로 작성합니다.
2. 이벤트에 실행할 자바스크립트 코드를 전달하는 것이 아니라, 함수 형태의 값을 전달합니다.
3. DOM 요소에만 이벤트를 설정할 수 있습니다.
div, button, input, form, span 등의 DOM 요소에는 이벤트를 설정할 수 있지만, 직접 만든 리액트 컴포넌트에는 이벤트를 자체적으로 설정할 수 없다.
<MyComponent onClick={doSomething} />
이 코드는 이름이 onClick 인 props 를 컴포넌트에 전달할 뿐이다.
컴포넌트에 자체적으로 이벤트를 설정할 수는 없지만, 전달받은 props 를 컴포넌트내부의 DOM 이벤트로 설정할 수는 있다.
<div onClick={this.props.onClick}>{/* ... */}</div>
'클래스형 컴포넌트'
import React, {Component} from 'react';
class EventPractice extends Component {
state = {
username: '',
message: '',
};
handleChange = (e) => {
this.setState({
[e.target.name]: e.target.value,
});
};
handleClick = () => {
alert(this.state.username + ': ' + this.state.message);
this.setState({
username: '',
message: '',
});
};
render() {
return (
<div>
<h1>Event Practice</h1>
<input
type="text"
name="username"
placeholder="User name"
value={this.state.username}
onChange={this.handleChange}
/>
<input
type="text"
name="message"
placeholder="type something"
value={this.state.message}
onChange={this.handleChange}
/>
<button onClick={this.handleClick}>Submit</button>
</div>
);
}
}
export default EventPractice;

- EventPractice 컴포넌트에 input 요소를 렌더링하는 코드와 해당 요소에 onChange 이벤트 설정
- e 객체는 SyntheticEvent로 웹 브라우저의 네이티브 이벤트를 감싸는 객체
- SyntheticEvent는 네이티브 이벤트와 달리 이벤트가 끝나고 나면 이벤트가 초기화되므로 정보를 참조할 수 없음
- 만약 비동기적으로 이벤트 객체를 참조할 일이 있다면 e.persist() 함수를 호출해야 함
- 함수를 미리 준비하여 전달하는 방법 → 가독성이 더욱 높음
- constructor 함수에서 함수를 바인딩하는 작업이 이루어짐
- input이 여러 개일 때는 event 객체를 활용하는 것이 쉽게 처리할 수 있음
- onChange 이벤트 핸들러에서 e.target.name은 해당 input의 name을 가르킴
handleChange = (e) => {
this.setState({
[e.target.name]: e.target.value,
});
};
- e.target.name을 [ ]로 감싸는데, 이렇게 객체 안에서 key를 [ ]로 감싸면 그 안에 넣은 레퍼런스가 가르키는 실제 값이 key 값으로 사용됨
'함수형 컴포넌트'
import React, { useState } from "react";
const EventPractice = (props) => {
const [username, setUsername] = useState("");
const [message, setMessage] = useState("");
const onChangeUsername = (e) => setUsername(e.target.value);
const onChangeMessage = (e) => setMessage(e.target.value);
const onClick = () => {
alert(username + ": " + message);
setUsername("");
setMessage("");
};
const onKeyPress = (e) => {
if (e.key === "Enter") {
onClick();
}
};
return (
<>
<h1>이벤트연습</h1>
<input
type="text"
name="messge"
placeholder="아무거나 입력"
value={username}
onChange={onChangeUsername}
></input>
<input
type="text"
name="messge"
placeholder="아무거나 입력"
value={message}
onChange={onChangeMessage}
onKeyPress={onkeypress}
></input>
<button onClick={onClick}>확인</button>
</>
);
};
export default EventPractice;
- e.target.name을 활용하지 않고 onChange 관련 함수 두 개를 따로 만들어줌
- 인풋의 개수가 많아질 것 같다면 e.target.name을 활용하는게 더 좋을 수도 있음
import React, {useState} from 'react';
const EventPractice = (props) => {
const [form, setForm] = useState({
username: "",
message: ""
});
const { username, message } = form;
const onChange = (e) => {
const nextForm = {
...form, // 기존의 form 내용을 이 자리에 복사한 뒤
[e.target.name]: e.target.value // 원하는 값을 덮어 씌우기
};
setForm(nextForm);
};
const onClick = () => {
alert(username + ": " + message);
setForm({
username: "",
message: ""
});
};
const onKeyPress = (e) => {
if (e.key === "Enter") {
onClick();
}
};
return (
<>
<h1>이벤트연습</h1>
<input
type="text"
name="messge"
placeholder="아무거나 입력"
value={username}
onChange={onChange}
></input>
<input
type="text"
name="messge"
placeholder="아무거나 입력"
value={message}
onChange={onChange}
onKeyPress={onKeyPress}
></input>
<button onClick={onClick}>확인</button>
</>
);
};
export default EventPractice;
- useState를 통해 사용하는 상태에 문자열이 아닌 객체를 넣음
- e.target.name 값을 활용하려면, useState를 쓸 때 인풋 값들이 들어 있는 form 객체를 사용해주면 됨
'결론 및 정리'
클래스형 컴포넌트 vs 함수형 컴포넌트
클래스 컴포넌트는 라이프 사이클 기능 및 state 관리 기능을 사용할 수 있으며, 임의 메서드를 정의할 수 있다.
함수형 컴포넌트는 hook을 통해 라이프 사이클 기능과 state 관리 기능 코드를 짤 수 있으며, 클래스형 컴포넌트보다 선언하기 더 편하고, 메모리 자원을 덜 사용한다는 장점이 있다. 또한, 사이클 API를 사용할 수 없다는 단점이 있었지만, hook이 도입되면서 해결되었다.
- 리액트에서 이벤트를 다루는 것을 순수 자바스크립트 또는 iQuery를 사용한 웹 애플리케이션에서 이벤트를 다루는 것과 비슷하다.
- 기존 HTML DOM Event를 알고 있다면 리액트의 컴포넌트 이벤트도 쉽게 따를 수 있다.
- 8장의 useReducer와 Hooks를 사용하면 더 편하게 만들 수 있다.
'React' 카테고리의 다른 글
6# 컴포넌트 반복 (0) | 2023.01.27 |
---|---|
5# ref: DOM에 이름 달기 (0) | 2023.01.13 |
3# 컴포넌트 (0) | 2022.12.30 |
2# JSX (0) | 2022.12.23 |
1# 리액트 시작 (0) | 2022.12.23 |