import { useState } from 'react'
const EventPractice = () => {
const [message, setMessage] = useState('')
const handleClick = () => {
alert(message)
}
const handleKeyPress = (e) => {
if (e.key === 'Enter') {
alert(message)
}
}
return (
<div>
<h1>이벤트 연습</h1>
<input
type="text"
name="message"
placeholder="아무거나 입력해 보세요"
onChange={(e) => {
setMessage(e.target.value)
}}
onKeyPress={handleKeyPress}
/>
<button onClick={handleClick}>확인</button>
</div>
)
}
export default EventPractice
import { useState } from 'react'
const EventPractice = () => {
const [username, setUsername] = useState('')
const [message, setMessage] = useState('')
const onChangeUssername = (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') {
alert(message)
}
}
return (
<div>
<h1>이벤트 연습</h1>
<input
type="text"
name="username"
placeholder="사용자명"
onChange={onChangeUssername}
value={username}
/>
<input
type="text"
name="message"
placeholder="아무거나 입력해 보세요"
value={message}
onChange={onChangeMessage}
onKeyPress={onKeyPress}
></input>
<button onClick={onClick}>확인</button>
</div>
)
}
export default EventPractice
📌
import { useState } from 'react'
const EventPractice = () => {
const [form, setForm] = useState({
username: '',
message: '',
})
const { username, message } = form // 비구조화할당
const onChange = (e) => {
const newForm = {
...form,
[e.target.name]: e.target.value,
// [] 넣어줌으로서 객체 생성과 동시에 동적인 key값 설정
}
setForm(newForm)
}
const onClick = () => {
alert(username + ': ' + message)
}
const onKeyPress = (e) => {
if (e.key === 'Enter') {
alert(message)
}
}
return (
<div>
<h1>이벤트 연습</h1>
<input
type="text"
name="username"
placeholder="사용자명"
onChange={onChange}
value={username}
/>
<input
type="text"
name="message"
placeholder="아무거나 입력해 보세요"
value={message}
onChange={onChange}
onKeyPress={onKeyPress}
></input>
<button onClick={onClick}>확인</button>
</div>
)
}
export default EventPractice