본문 바로가기
TIL

Plmography 프로젝트 작업 로그 #36 - 콜백 함수에 매개변수 전달하기(23.01.17 TIL)

by winteringg 2023. 1. 17.

댓글 등록 버튼을 만들 때 onSubmit 함수 매개변수로 댓글이 달리는 post 의 아이디를 넘겨주고 싶었다.

// onSubmit 함수
const handleSubmit = async (e, review) => {
    e.preventDefault();

    commentFormStore.validate();

    if (commentFormStore.isValidateSuccessful) {
      await commentStore.create(userId, review.id, commentFormStore.body);
    }
};


// 버튼 태그
{commentButtonOpened && (
  <CommentForm
    onSubmit={() => handleSubmit(e, review)}
  />
)}

이런 식으로 넘겨주었더니 preventDefault 가 작동하지 않고 계속 새로고침 되었다. 알고보니 이벤트를 실행하게 하려면 콜백함수에서도 이벤트 (e) 를 넘겨주어야 한다고 한다.

// 버튼 태그
{commentButtonOpened && (
  <CommentForm
    onSubmit={(e) => handleSubmit(e, review)}
  />
)}

그래서 이렇게 콜백함수에 이벤트를 넣어서 한 번 더 전달해주니 제대로 작동했다!

댓글