DiaryEditor.js
import { useState } from 'react';
const DiaryEditor = () => {
const [author, setAuthor] = useState('임하나');
const [content, setContent] = useState('내용');
return(
<div className="DiaryEditor">
<h2>오늘의 일기</h2>
<div>
<input
value={author}
onChange={(e)=>{
setAuthor(e.target.value)
}}
/>
</div>
<div>
<textarea
value={content}
onChange={(e)=>{
setContent(e.target.content);
}}
/>
</div>
</div>
)
}
export default DiaryEditor;
import { useState } from 'react';
const DiaryEditor = () => {
const [author, setAuthor] = useState('임하나');
const [content, setContent] = useState('내용');
return(
<div className="DiaryEditor">
<h2>오늘의 일기</h2>
<div>
<input
value={author}
onChange={(e)=>{
setAuthor(e.target.value)
}}
/>
</div>
<div>
<textarea
value={content}
onChange={(e)=>{
setContent(e.target.content);
}}
/>
</div>
</div>
)
}
export default DiaryEditor;
동작 방식이 같음으로, 묶어줄 수있다.
(요소가 길어질 수 있기 때문에 스프레이 연산자 사용.)
const DiaryEditor = () => {
const [state, setState] = useState({
author:"",
content:"",
})
return(
<div>
<input
value={state.author}
onChange={(e)=>{
setState({
...state,
author : e.target.value
})
}}
/>
</div>
<div>
<textarea
value={state.content}
onChange={(e)=>{
setState({
...state,
content:e.target.value
})
}}
/>
</div>
)
}
export default DiaryEditor;
const [state, setState] = useState({
author:"",
content:"",
});
const handleChangeState = (e) => {
setState({
...state,
[e.target.name] : e.target.value,
})
}
<input
name='author'
value={state.author}
onChange={handleChangeState}
/>
<textarea
name='content'
value={state.content}
onChange={handleChangeState}
/>
const handleSubmit = () => {
console.log(state);
alert('저장성공')
}
<button onClick={handleSubmit}>일기 저장하기</button>