{commentArray.maap((comment) => {
return <li key=(comment.id)>{comment.content}</li> //map 사용시에 식별할 수 있는 key가 필요, 최상위 tag에 key를 넣어야함.
⏬ ⏬ ⏬
<li>
가 길어지기 때문에 분리필요. 컴포넌트화 시켜줄 것임.
Comments.js
로 컴포넌트화 시켜주고 본래자리에는 <Comments />
기재하기
그 밑에는 li에 들어갈 내용 기재해줄 것임
<Feed.js>
{commentArray.map((comment) => {
return (
<li key={comment.id}>
<Comments
id={comment.id}
content={comment.content}
author={"익명"}
createdAt={comment.createdAt || "2022-01-01"}/>//createdAt 값이 없으면 2022-01-01로 입력
</li>
<Comments.js>
function Comments(props) {
const { id, content, author, createdAt } = props; //구조분해 할당
return {
<span>
{content} - {author}
<span className="createdAt"> {createdAt} </span>
Feed
함수 안에 입력값에 대한 useState
입력function Feed() {
const [inputstate, setInput] = useState(""); //초기값은 빈칸으로 둠
addComment
함수 newComment
항목에 inputState
가져옴.const addComment= () => {
setId(id + 1)
const newComment = {
id: id,
content: inputState,
createdAt: new Date().toLocaleString(),
};
setInput("") //상태값 변화 후 ""
setCommentArray([...commentArray, newComment]);
};
Enter
누르면 게시물 등록할 수 있게 구현onKeyPress
함수 만들어서 addComment
함수 불러오기
const onKeyPress = (e) => {
if (e.key === "Enter") {
addComment();
}
};
onKeyPress
함수를 댓글 입력 부분에 적용하기
<input>
className="commentinput"
type="text"
placeholder="댓글 달기..."
ref={value}
value={inputState}
onChange={(e) => setInput(e.target.value)}
onKeyPress={onKeyPress}/>입력하세요 // 원래 onKeyDown 이었으나 한글 입력시 마지막 글자가 중복으로 재입력되어 onKeyPress로 변경
key
값이 없으면 순서 구별을 못함.
➡️ key
는 index
가 아닌 고유값
이 들어가야함.
자세한 것은 아래 사이트 참고
https://ko.reactjs.org/docs/lists-and-keys.html