사용자가 댓글 입력 후 enter 를 누르거나 왼쪽의 버튼 클릭 시 댓글이 추가되도록 구현해주세요.
댓글 기능을 구현하기 위해서는 배열 데이터 타입을 활용해야 합니다.
Array.map 참고해서 시도해주세요.
위 순서대로 완료 후 Add : Mission 3 - 댓글 기능 구현 commit message를 남긴 후 push 해주세요.
1.state 값을 먼저 선언한다.
const [comment, setComment] = useState('');
2.handleCommentInput
함수가 setComment
에 저장되도록 한다
const handleCommentInput = event => {
const { value } = event.target;
setComment(value);
// const handleCommentInput = event => {
// setComment(event.target.value);
// };
<input
type="text"
className="comment-box"
placeholder="댓글을 입력하세요"
value={comment} />
4 onChange 이벤트를 실행시키기 위해 commentInput 함수를 넣어준다.
<input
type="text"
className="comment-box"
placeholder="댓글을 입력하세요"
value={comment}
onChange={handleCommentInput}
1.배열이 저장될 수 있도록 state 값을 빈배열로 선언한다.
const [commentArray, setCommentArray] = useState([]);
2.입력한 댓글이 등록될 수 있돌고 onSubmit 이름으로 함수를 선언하고 이 함수 안에서 입력된 comment 값이 배열로 출력될 수 있도록 지정해준다. 또한, 아무 입력이 없다면 전송되지 않도록 설정해준다.
const onSubmit = event => {
let copy = [...commentArray];
copy.push(comment);
setCommentArray(copy);
setComment('');
};
3.버튼태그에 onClick 이벤트를 주어서 클릭 이벤트 발생시
위에 지정한onSubmit
함수가 실행 되도록 한다
<button className="comment-btn" onClick={onSubmit}>
4.enter키를 눌렀을때도 해당 함수가 실행되도록 해주어야하기에
input 태그에도 onKeyPress를 주어서 entet
키를 눌렀을때
onSubmit함수
가 실행되도록 설정해준다
onKeyPress={function (e) {
if (e.key === 'Enter') {
onSubmit();
}
}}
map method를 이용하여 value 값이 입력되면 commentArray 배열 안에 저장될 수 있게 하여 div tag 안의 p tag 가 출력될 수 있도록 설정해준다.
{{commentArray.map(function (a, i) {
return <p>{commentArray[i]}</p>;
})} }