멈멈-토이프로젝트(next.js)2
댓글 수정, 취소
순9
2024. 9. 28. 22:33
728x90
수정 폼에서 수정데이트 등록 후 또는 취소 클릭시 이전 화면으로 돌아오기
콜백 함수 사용
댓글 컴포넌트
const [editClick, setEditClick] = useState(0);
//수정 ui 보이게 하는 함수
const handleEditComment = (id: number) => {
setEditClick(id);
};
// 수정ui 안보이게 하는 함수
const handleEditComplete = () => {
setEditClick(0);
};
<CommentEdit onEditComplete={handleEditComplete} />
수정 컴포넌트
export default function CommentEdit({
onEditComplete,
}: {
onEditComplete: () => void;
}) {
const handleComment = (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault();
try {
fetch("/api/comment-edit", {
method: "PUT",
body: JSON.stringify(requestBody),
});
onEditComplete();
setTextValue("");
} catch (error) {}
};
return (
<form onSubmit={handleComment} style={{ border: "1px solid #999" }}>
<textarea
name="content"
defaultValue={content}
onChange={(e) => setTextValue(e.target.value)}
placeholder="내용을 입력해주세요"
required
></textarea>
<button type="submit">등록</button>
<button type="button" onClick={onEditComplete}>
취소
</button>
</form>
);
}
콜백 함수의 흐름
1. 부모 컴포넌트에서 handleEditComment 함수에서 댓글 id 보내서 관련
자식 컴포넌트 댓글 수정 할 수 있는 폼이 출력 여기에서 등록 또는 취소 할 수 있음
2. 부모 컴포넌트에서 handleEditComplete 함수에서
editClick 상태를 0으로 설정 수정 모드를 종료 할 수 있도록 설정
3. 자식 컴포넌트에서 onClick={onEditComplete} (등록, 취소 버튼)클릭시 함수 호출
4. editClick 상태를 0 돌아 와서 수정 폼이 사라짐