[(과제) [React] State, Props, Event] - 4

장운서·2021년 6월 30일
0

react

목록 보기
5/9
post-thumbnail

Mission 4) Main | 댓글 컴포넌트화 + props로 데이터 전달

  • map 함수를 활용해 댓글 목록을 구현해주세요.
  • 댓글 하나를 컴포넌트화 시켜주세요.
  • 부모의 state 에 저장된 댓글 데이터에 Array.map() 메소드를 적용해 댓글의 개수만큼 댓글 컴포넌트가 나타나게 해주세요.
  • 필요한 데이터를 props 로 넘겨주세요.
  • 기존에 보였던 대로 댓글이 화면에 나타나면 과제 완료입니다.
  • 위 순서대로 완료 후 Add : Mission 4 - 댓글 컴포넌트화, props로 데이터 전달 구현 commit message를 남긴 후 push 해주세요.


import React from 'react';

class Comment extends React.Component {
  render() {
    const { comment } = this.props;
    return (
      <li>
        <span className="id-wrap">
          <a href="#!" tabIndex="0" className="comment-id">
            kimdaebeom
          </a>
        </span>
        <span>{comment}</span>
      </li>
    );
  }
}

export default Comment;

1. comment 파일 생성

Comment.js로 댓글창을 다루는 컴포넌트를 따로 분리 시켜주었다.
props로 자식에서 부모 컴포넌트로 값을 넘겨준다.
직관성을 위해서 this.props를 const로 변수화 시켜주었다.

<ul className="list">
  {commentList.commentList.map(el => {
    return <Comment key={el.key} comment={el.comment} />;
  })}
</ul>
addComment = e => {
    const { commentList } = this.state; //구조분해할당
    this.setState({
      commentList: commentList.concat({ comment: this.state.commentValue }),
      commentValue: '',
      value: '',
    });
    e.preventDefault();
  };

2. map함수 로 Comment의 내용

  • const commentList = this.state;로 직관성을 높혀주었다.
  • react에서 js 를 적용할때엔 {}를 쳐서 적어준다.
  • map메소드로 comment를 반환합니다.
  • map메소드를 적용해 댓글의 개수만큼 댓글 컴포넌트가 나타나게 해준다.

어려운건 없엇지만 mockdata를 적용시키면서 해당 데이터를 가져오는 부분이 너무 어려웠다.

profile
방향성을 찾고싶은 프론트엔드개발자

0개의 댓글