역시나 어려웠던 댓글창 구현!
👉Main component
class Main extends React.Component {
constructor() {
super();
this.state = {
id: '',
stateComment: '',
comments: [],
};
}
stateComment = e => {
const commentValue = e.target.value;
this.setState({ stateComment: commentValue });
if (e.key === 'Enter') {
e.target.value = '';
}
};
plusComment = e => {
e.preventDefault();
const newComment = this.state.stateComment;
this.setState({
comments: this.state.comments.concat(newComment),
stateComment: '',
});
};
<div className="commentBox">
<form onSubmit={this.plusComment}>
<input
className="lightFontColor comment"
type="text"
placeholder=" 댓글 달기..."
onKeyUp={this.stateComment}
/>
<button className="commentBtn" type="submit">
게시
</button>
</form>
</div>
👉Main component
componentDidMount() {
fetch('http://localhost:3000/data/commentData.json', {
method: 'GET',
})
.then(res => res.json())
.then(data => {
this.setState({
comments: data,
});
});
}
<div className="commentViewBox center">
{this.state.comments.map(comment => {
return (
<Comment
key={comment.id}
name={comment.userName}
comment={comment.content}
/>
);
})}
</div>
👉Comment component(Main component의 자식)
class Comment extends React.Component {
render() {
console.log(this.props);
return (
<li className="commentFlex">
<span className="boldFont">{this.props.name}</span>
<div>
<span className="commentStyle">{this.props.comment}</span>
</div>
</li>
);
}
}