constructor() {
super();
this.state = {
name: "",
id: 3,
commentInput: "",
commentData: [
{
id: 0,
userId: "홍효정",
comment: "집에 가고싶어요",
like: false
},
{
id: 1,
userId: "wecode_bootcamp",
comment: "화이팅",
like: true
},
{
id: 2,
userId: "홍효정",
comment: "ㅠㅠ",
like: false
},
],
};
}
main feed 댓글의 state 초기값을 정의한다.
handleCommentChange = (e) => {
this.setState({
commentInput: e.target.value,
});
};
댓글 input
에 값이 들어오면 해당input
의 value값을 commentInput에 저장한다.
handleCommentCreate = () => {
const { commentData, commentInput } = this.state;
if (commentInput.length > 0) {
this.setState({
commentData: commentData.concat({
id: this.state.id,
userId: "홍효정",
comment: commentInput,
like: false,
}),
id: this.state.id + 1,
commentInput: "",
});
}
};
댓글 생성 함수. 현재 state중 commentData와 commentInput을 받아와서 input
에 값이 있을때 함수 실행시 concat
메서드로 새로운 댓글 컴포넌트를 만든다.
handleCommentClickAdd = () => {
this.handleCommentCreate();
};
handleCommentKeypressAdd = (e) => {
if (e.key === "Enter") {
this.handleCommentCreate();
}
};
게시 버튼을 클릭하거나 키보드 enter를 치면 댓글 생성 함수를 실행한다.
handleCommentLike = (id) => {
const { commentData } = this.state;
const index = commentData.findIndex(
(commentData) => commentData.id === id
);
const selected = commentData[index];
const nextCommentData = [...commentData]; // spread syntax
nextCommentData[index] = {
...selected,
like: !selected.like,
};
this.setState({
commentData: nextCommentData,
});
};
배열의 값을 직접 수정하지 않고 spread syntax(전개연산자)를 활용했었던 좋아요 기능. 클릭한 댓글의 인자로 받아온 id
와 commentData배열안의 id
를 findIndex
메서드로 찾아와서 일치하면 그 index
인 배열의 state like를 true
, false
로 전환한후 setState한다.
handleCommentDelete = (id) => {
const { commentData } = this.state;
this.setState({
commentData: commentData.filter(
(commentData) => commentData.id !== id
),
});
};
클릭한 댓글의 id
를 갖고있지 않는 배열을 filter
메서드로 생성하여 commentData로 setState한다.