const [commentArray, setCommentArray] = useState([
{
id: 0,
content: "싸우지 마ㅠ",
},
]);
ui 태그 여기서는 li 태그를 개 수 만큼 리턴해줘야하기 때문에 map함수를 사용해야한다. (map함수와 foreach의 차이점?)
<div className="feed-comment-list">
{commentArray.map((comment) => {
return <li key={comment.id}>{comment.content}</li>;
})}
</div>
(comment)
는 map 함수의 필수 요소로 commentArray의 요소들을 지칭한다.<li>
에 key값을 부여하지 않으면 오류가 난다. map 함수는 하나씩 반환하기 때문에 식별할 수 있는 key 값이 필요하기 때문이다. 보통 id값을 key값으로 사용한다 (왜 인덱스는 안쓰는지?)버튼을 눌렀을 때 input에 있는 값이 feed-comment-list에 state로 추가되는 함수가 실행되어야한다.
이는 두가지 방식으로 구현할 수 있는데
1) input 에 onChange 이벤트를 사용하는 방법과
2) useRef라는 Hook을 사용하는 방법이 있다.
const [comment, setComment] = useState();
<input className="comments-input" type="text" placeholder="댓글 달기..."
onChange={(e) => {onChange={(e) => {setComment(e.target.value);}} />
const [id, setId] = useState(1);
const [commentArray, setCommentArray] = useState([
{
id: 0,
content: "싸우지 마ㅠ",
},
]);
const addComment = () => {
setId(id + 1);
const newComment = {
id: id,
content: comment,
};
setCommentArray([...commentArray, newComment]);
};
.push
를 하지 않는 이유는 자바스크립트에서만 사용하는 문법이라 리액트가 못알아들어서 렌더링이 안되기 때문이다.<button className="upload-button" onClick={addComment}>
게시
<button/>
const value = useRef();
<input className="comments-input" type="text" placeholder="댓글 달기..."
ref={value} />
const addComment = () => {
setId(id + 1);
const newComment = {
id: id,
content: value.current.value,
};
setCommentArray([...commentArray, newComment]);
};