[React] 댓글 구현 3 (setState 활용)

문병곤·2020년 12월 13일
0

리액트 라이브러리의 핵심 기능 중 하나가 render다. 이를 구현시킬 때는 this.statethis.setState가 자주 이용된다. 전자가 기본 토대(?)라면 후자는 가상DOM에서 this.state을 조작한 뒤 브라우저에서 구현될 때 필요하다.

이를 이용해서 댓글을 작성하는 기능을 구현해봤다.

class Comment extends Component {
  constructor() {
    super();
    this.state = {
      value: "",
      commentList: [],
    };
  }

먼저 this.state에 value와 commentList라는 키값을 주었다. 특히 commentList에는 빈 배열을 값으로 주었다. map함수를 사용해서 배열을 수정해야하기 때문이다.

먼저 map 함수를 이용해this.state.commentList에 들어갈 내용을 작성했다. idx(index)를 통해 0부터 시작하는 숫자를 id로 할당했다. comm은 미정의 내용을 의미한다.

 {this.state.commentList.map((comm, idx) => {
          return (
            <li id={idx} className="comment">
              <a href="https://www.instagram.com/" className="userId">
                {"moonvenn_dev "}
              </a>
              {comm}
            </li>
          );
        })}

다음으로 e 라는 특정 이벤트가 발생했을 때 value가 e.target.value로 변하는 코드를 작성했다. 이때 this.setState가 필요하다.

pushComment = (e) => {
    this.setState({
      value: e.target.value,
    });
  };

여기서 value는 다음과 같다.

  <input
         type="text"
         id="createComment"
         placeholder="댓글 달기..."
         onfocus="this.placeholder=''"
         onChange={this.pushComment}
         onKeyPress={this.addCommentEnter}
         value={this.state.value}
   />

나는 input의 onChange에 이벤트 값을 주었다. input에 어떠한 변화가 일어나는 것을 이벤트로 정한 것이다. 그리고 보다시피 value는 this.state.value로 할당해줬다.

  addComment = () => {
    const { commentList, value } = this.state;
    this.setState({
      commentList: commentList.concat([value]),
      value: ""
    });
  };

이제 setState를 통해 commentList 배열을 업데이트 시켜줬다. 이때 사용한 함수는 concat으로, 기존 배열에 원소 또는 배열을 추가하여 새 배열을 만드는 함수다.

그 밑에 달린 value: ""는 댓글을 작성한 뒤 input 칸을 새로 리셋하는 코드다. 댓글을 작성했음에도 칸에 아직 글씨가 남는 것을 방지하기 위함이다.


이를 사용하기 위해 button에 onClick을 주었다. 다음이 그러하다. className={activateBtn ? "active" : ""}은 댓글이 입력되었을 때 게시라는 글자의 색이 바뀌게 하기 위함이다.

//react
<button
            id="pushComment"
            className={activateBtn ? "active" : ""}
            onClick={this.addComment}
          >
//scss
  #pushComment {

    color: skyblue;
    
    &.active {
      color: blue;
      cursor: pointer;
    }
}

이 밖에도 굳이 게시 버튼을 누르지 않고 엔터를 누르면 댓글이 입력되는 기능을 구현했다. input에 onKeyPress={this.addCommentEnter}를 준 뒤 사용하면 된다.

 addCommentEnter = (e) => {
    if (e.key === "Enter") {
      this.addComment();
    }
  };

0개의 댓글