[TIL] React 버튼 onClick 기능에 함수 2개 주고 싶어..

Eden·2022년 8월 31일
4

TIL

목록 보기
11/23
post-thumbnail

클론 코딩을 진행하는 중에

댓글 기능 구현을 하는데, input창에 댓글을 입력하면 그 값을 받아와서 댓글 등록 버튼을 누르면 댓글 리스트에 댓글이 올라가고, 댓글 갯수가 카운트 되는 기능을 구현해야 했다.

나는 Comment 컴포넌트 안에서 댓글을 추가할 기능인 addComment함수와 댓글 갯수를 카운트 해주는 함수인 count를 먼저 선언해주었다.

<script>
function Comment() {

...(생략)...

  const addComment = () => {
      // event.preventDefault();
      // console.log(event.target.value);
      setId(id + 1);
      // console.log(id);

      const newComment = {
        id: id,
        profile: <img src="/images/user.png" width="25px" height="25px" />,
        user: "eden",
        date: "2022-08-30",
        content: comment,
      };
      // console.log(1, newComment);
      setCommentArray([...commentArray, newComment]);
      // console.log(commentArray);
      setComment("");
    };

    const count = () => {
      setCommentCount(commentCount + 1);
    };

  ...(생략)...
  
</script>
<script>

      <input 
          type="text"
          value={comment}
          className={styles.commentInput}
          placeholder="댓글을 입력하세요."
          onChange={(event) => {
              setComment(event.target.value);
            }}
         />

        <div className={styles.commentButton}>
            <button
               type="submit"
               onClick={() => {
                  addComment();
                  count();
                  }}
                > </>

          
          ...(생략)....
          
          
 }
 
 </script>

onClick 이벤트 안에 화살표 함수를 열어주고 return에 함수를 나란히 호출해주면 된다!

profile
one part.

0개의 댓글