React_Mission 4. 댓글업로드 기능 컴포넌트화 시키기

ha ju·2021년 5월 4일
0
post-thumbnail

React_Mission 4. 댓글업로드 기능 컴포넌트화 시키기

1. 우선 우리가 컴포넌트화 시켜야할 부분을 알아보자

   <form className="feeds_upload_comments">
      <li>
         <span className="comment_writer">yyeon_jju</span>
         <span className="comment_content">너무 예뻐요~~</span>
     </li>
         {this.state.commentList.map((comment, idx) => { 
            return <li key={idx}>{comment}</li>;          //⭐이 부분 컴포넌트화 시키기
            })}
  </form>
  • 댓글을 업로드 시킬때마다 화면상에 <li>로 렌더링되길 희망하기 때문에 return 부분을 컴포넌트화 시키면 될 것이다.
    🍒 컴포넌트 생성 방법이 궁금하다면 블로그에 Component 생성 및 적용하는 법이라는 글을 참고하면 놓치는 부분 없이 부모 컴포넌트에 import까지 할 수 있을 것이다.
  • 나는 Comment라는 컴포넌트를 만들어줄 것이기 때문에 위의 코드를 아래처럼 수정하였고,
    컴포넌트 태그 안에는 commentList배열의 각 요소들을 comment라는 이름으로 props를 전달하였다.
   <form className="feeds_upload_comments">
      <li>
         <span className="comment_writer">yyeon_jju</span>
         <span className="comment_content">너무 예뻐요~~</span>
     </li>
         {this.state.commentList.map(commentElement => {
             return <Comment comment={commentElement} />;
           })}
  </form>

2. Comment.js

나는 Comment라는 컴포넌트로 쪼개주었고 Comment.js파일의 코드는 아래와 같다

class Comment extends React.Component {
  render() {
    const { comment } = this.props;
    return (
      <form>
        <li>{comment}</li>
      </form>
    );
  }
}

export default Comment;
  • 여기서도 구조 분해 할당을 통해 인자로 받은 요소를 변수로 정의해주었고 이때문에 <li>{comment}</li>에서 중괄호 안을this.props.comment가 아닌 comment로 써줄 수 있는 것이다.
  • this.state와 마찬가지로 this.props의 값들도 구조분해 할당으로 props명과 같은 변수를 만들어 간략하게 적어줄 수 있다.

1개의 댓글

comment-user-thumbnail
2021년 5월 5일

연쥬님 짱부지런.......👏👏👏

답글 달기