리액트 댓글기능 구현하기

DevOps 블로그·2021년 12월 22일
0

Self-memo를 위해서 기록을 남긴다.

  1. input 태그에 댓글을 입력하면 그 입력된 값이 state에 저장되게 한다.
{/* <input> 태그의 value 속성은 <input> 요소의 초깃값(value)을 명시합니다. */}
{/* value로 input 태그의 초기값으로 commentValue를 준다. 그리고 input에 담긴 값을 처리한 후에, 
다시 value에 commentValue에 ''을 줌으로서 input 태그를 초기화 한다.(uploadComment) */}


<input
 onChange={handleCommentInput}
 className="input_comment"
 type="text"
 value={commentValue}
  placeholder="댓글 달기..."
/>

//input에서 값의 변화가 일어나면 아래의 함수를 실행한다. event 값을 감지하고 그것을 updateComment에 보낸다.
  
 function handleCommentInput(event) {
    updateComment(event.target.value);
  }

그리고 updateComment함수로 event.target.value는 commentValue라는 state에 담긴다.
여기서 input 태그의 value에 {commentValue}를 넣어준 이유는 input에 댓글 내용을 입력하고 그것이 댓글로 달린 후에 input 태그에 아무런 값이 남지 않고 "댓글 달기..." 남아주기 위한 초기화 장치이다.

 <input> 태그의 value 속성은 <input> 요소의 초깃값(value)을 명시합니다.
 -TCP School
 출처: http://tcpschool.com/html-tag-attrs/input-value


  
  1. 버튼을 누르면 input에 입력된 값이 댓글로 달리게 한다.
    버튼에 onclick 함수를 만들어 준다. 그리고 uploadComment함수가 실행이 된다.
<button className="comment_btn" onClick={uploadComment}>
   게시
</button>


* Comment component를 댓글에 달릴 곳에 넣어준다.
  // Comment (name, commentValue) 형태로 한다. 
  	왜냐하면 아이디가 있고 댓글이 달리기 때문이다.
  // {name: '값', commentValue: '값' }
  //props.name이 아이디가 되고, commentValue가 댓글 내용이 된다.
  
  const Comment = props => {
    return (
      <div className="comment">
        <span>{props.name}</span>
        <span> {props.comment}</span>
      </div>
    );
  };


{/* 변경된 값이 담긴 listComments에 map을 해준다.(배열 내의 모든 요소 가각에 대하여 주어진 함수를 호출한 결과를 모아 새로운 배열로 반환) */}
{/* listComment는 내가 지정한 인자이다. 이 인자는 배열 내의 { name: '', comment: '' }이다. */}
{/* Comment component를 써서 부른다. 단, name key의 값은 listComment.name이고 comment의 key값은 listComment.comment이다. */}
                
                
                
//listComment는  {name: '값', commentValue: '값' }가 전달 되는 것이다.             
  <div>
   {listComments.map(listComment => (
    <Comment
      name={listComment.name}
      comment={listComment.comment}
	 />
    ))}
  </div>



 //uploadComment함수는 실행되면
  //listComments를 spread 전개구문 복사해서 newlistComments에 담는다. 
	왜냐하면 state를 직접적으로 수정해서는 안되기 떄문이다.
  //newlistComments에 { name: 'testID', comment: commentValue(input에 담긴 값) } push 해준다.
  //값이 최종 변경된 newlistComments를 listComments에 넣어서 state가 간접적으로 변경되게 한다.
 //이벤트처리는 한 태그에 한번만사용 가능 그러므로 이 안에서 다 처리해야 함
 
  function uploadComment() {
    let newlistComments = [...listComments];
    newlistComments.push({ name: 'testID', comment: commentValue });
    setListComments(newlistComments);
    
    updateComment('');
  }
  1. Component를 내가 넣고자 하는 위치에 넣는다. Comments component 안에 있는 name은 props로 전달된 { name: '', comment: '' }의 name의 값{listComment.name}을 받아서 출력, comment는 comment의 값({listComment.comment})을 받아서 출력한다.
  • 수정점: 코드가 중구난방이고, 아직까지 리액트의 이해가 완전하지 못하다. 좀더 공부하고 Component도 분리해서 따로 파일 작성하는 식으로 해서 다시 코드를 정리해서 작성할 필요가 있다.
profile
IT 엔지니어를 향해 살아가는, 공부하는 기록들을 모아두고 있습니다.

0개의 댓글