TIL_React사용_props 사용

이고운·2022년 8월 18일
0

1. 피드, 댓글 컴포넌트화 + props로 데이터 전달하기

1) map함수 사용해서 피드, 댓글 목록 구현

2) 부모의 state에 저장된 댓글 데이터에 Array.map 메소드 적용해 댓글의 개수만큼 댓글 컴포넌트 나타나게 하기

{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>
      

3) 게시물 등록하면 입력칸에 글씨 없어지게 구현

  • 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]);
  };
  

4) 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로 변경
   

2. map함수 사용시에 key 입력해야하는 이유

key값이 없으면 순서 구별을 못함.
➡️ keyindex 가 아닌 고유값이 들어가야함.

자세한 것은 아래 사이트 참고
https://ko.reactjs.org/docs/lists-and-keys.html

profile
자 이제 시작이야~ 내 꿈을~ 내 꿈을 위한 여행~~🌈

0개의 댓글