
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한다.
Hey, this day is too much good for me, since this time I am reading this enormous informative article here at my home. Thanks a lot for massive hard work.situs toto
Thank you for such a well written article. It’s full of insightful information and entertaining descriptions. Your point of view is the best among many.toto
Relating to a short time ago begun a good webpage, the info everyone deliver on this website has got improved my family dramatically. Kudos meant for your whole point in time & job. anmol vachan
it is definitely excellent blog site. it is realy info as well as a a really beneficial task. i adore that. http://www.highdomainratingahref.top/
I found so many interesting stuff in your blog especially its discussion. From the tons of comments on your articles, I guess I am not the only one having all the enjoyment here! keep up the good work...MDR for Small Business