728x90
반응형
EX01
import { useState } from "react";
const EventPractice=()=>{
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(
<div>
<h1>이벤트연습</h1>
<input
type="text"
name="username"
placeholder="사용자명"
value={username}
onChange={onChangeUsername}
/>
<input
type="text"
name="message"
placeholder="아무글자나 입력"
value={message}
onChange={onChangeMessage}
onKeyPress={onKeyPress}
/>
<button onClick={onClick}>확인</button>
</div>
)
}
export default EventPractice;
EX02
import { useState } from "react";
const EventPractice=()=>{
const[form, setForm] = useState({
username:"",
message:""
})
const{username,message}=form;
const onChange=(e)=>{
const nextForm={
...form, //기존의 from내용을 이 자리에 복사
[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(
<div>
<h1>이벤트연습</h1>
<input
type="text"
name="username"
placeholder="사용자명"
value={username}
onChange={onChange}
/>
<input
type="text"
name="message"
placeholder="아무글자나 입력"
value={message}
onChange={onChange}
onKeyPress={onKeyPress}
/>
<button onClick={onClick}>확인</button>
</div>
)
}
export default EventPractice;
728x90
반응형
'Front-End > REACT' 카테고리의 다른 글
[REACT/JavaScript] map() (0) | 2022.12.08 |
---|---|
[REACT] list 추가, 삭제 - map, concat, filter (0) | 2022.12.08 |
[VSCode] 유용한 확장프로그램 (0) | 2022.12.05 |
[REACT] CMD를 이용해 REACT 개발환경을 설치하는 2가지 방법 - npm과 yarn (0) | 2022.12.05 |
[REACT] VSCode 코드 자동 완성 기능 추가 (0) | 2022.08.03 |
댓글