210309 WECODE #19 React 댓글기능 구현
Mission 3) Main | 댓글 기능
- 사용자가 댓글 입력 후 enter 를 누르거나 왼쪽의 버튼 클릭 시 댓글이 추가되도록 구현해주세요.
- 댓글 기능을 구현하기 위해서는 배열 데이터 타입을 활용해야 합니다.
Array.map
참고해서 시도해주세요.
.map( (e) => <li>e.text</li> )
: li와 .text 를 넣어서 실행시 ul에 li가 하나씩 추가되서 마치 댓글처럼 보이게 사용한다.
<textarea>
에 글을 작성할때 일단 아무것도 없도록 newReply = ""
를 넣어준다
- newReply에 들어온 값을
replies: [{text: "",}]
에 담아준다.
- state의
newReply: ""
를 setState
로 인해 작성한 값을 newReply의 value값으로 들어오게 만들었다.
{text: ""}
ㅡ> {text: this.state.newReply}
ㅡ> {text: e.target.value}
- 실행 후 setState로 인하여
textbox
에는 newReply: ""
과 replies: arr
이 실행
- ""를 다시 선언해주는 이유는 댓글이 달린 후, 다시 빈공간으로 초기화!
- 엔터를 치면 buttonClick함수 실행
- 그다음 입력한 value값을 ""로 초기화시켜 아무것도 없게 만든다
console.log를 찍어 확인해보자
import React from 'react';
import './Main.scss';
class Comment extends React.Component{
render(){
constructor(){
super();
this.state = {
newReply: "",
replies: [{ text: ""}]
};
}
textChange = (e) => {
this.setState({ newReply: e.target.value });
}
buttonClick = () => {
let arr = this.state.replies;
arr = arr.concat({ text: this.state.newReply });
this.setState({ newReply: "", replies: arr });
}
enterClick = (e) => {
if(e.key === "Enter"){
this.buttonClick;
e.target.value = "";
};
}
return(
<>
<ul className="textbox">{this.state.replies.map( (e) => (<li>e.text</li>) )}
</ul>
<textarea
className="comment_textarea"
placeholder="댓글 달기..."
onChange={this.textChange}
onKeyPress={this.enterClick}>
</textarea>
<button className="comment_button" onClick={this.buttonClick}>게시</button>
</>
)
}
}
Mission 4) Main | 댓글 컴포넌트화 + props로 데이터 전달
- map 함수를 활용해 댓글 목록을 구현해주세요.
- 댓글 하나를 컴포넌트화 시켜주세요.
- 부모의
state
에 저장된 댓글 데이터에 Array.map()
메소드를 적용해 댓글의 개수만큼 댓글 컴포넌트가 나타나게 해주세요.
- 필요한 데이터를
props
로 넘겨주세요.
- Comment.js에 존재하는 댓글 로직을 컴포넌트화를 해보겠다.
- props를 통해 부모 컴포넌트 내부의 state 값
(replies)
을 자식 컴포넌트에게 전달할 수 있다!