import { Component } from "react";
class EventPractice extends Component {
state = {
message: "",
username: ""
};
// 단일 핸들러로 state 업데이트 및 엔터키 처리
handleEvent = e => {
const { name, value, key } = e.target;
if (key === "Enter" || e.type === "click") {
this.setState({ message: "", username: "" });
} else {
this.setState({ [name]: value });
}
};
render() {
const { message, username } = this.state;
return (
<div>
<h1>이벤트 연습</h1>
<input
type="text"
name="message"
placeholder="입력해 보세요."
value={message}
onChange={this.handleEvent}
onKeyUp={this.handleEvent}
/>
<input
type="text"
name="username"
placeholder="입력해 보세요."
value={username}
onChange={this.handleEvent}
/>
<h2>message: {message}</h2>
<h2>username: {username}</h2>
<button onClick={this.handleEvent}>삭제</button>
</div>
);
}
}
export default EventPractice;