1 回答
TA贡献1848条经验 获得超10个赞
就我所知,您想添加一个用于提交新评论的表单,请写信?
尝试这个:
import React, { Component } from 'react';
import axios from 'axios';
class Comments extends Component {
state = {
Comment: [],
commentText: "",
};
componentDidMount() {
const { commentId } = this.props.location.state;
axios.get(`./hn_data/${commentId}.json`)
.then((res) => this.setState({ Comment: res.data }));
}
postComment() {
// add you comment to the database here
}
onCommentTextChange(event) {
this.setState({
commentText: event.currentTarget.value,
});
}
renderComments() {
return this.state.Comment.map(comment=>(
<p>{comment.text}</p>
));
}
renderForm() {
return (
<div class="comment-form">
<textarea
class="comment-form__text"
value={this.state.newCommentText}
onChange={(event) => this.onCommentTextChange(event)}
></textarea>
<button onClick={() => this.postComment()}>Submit</button>
</div>
)
}
render() {
console.log(this.state.Comment);
return (
<div>
{this.renderComments()}
{this.renderForm()}
</div>
)
}
}
export default Comments;
在 postComment 中,您可以将 this.state.commentText 添加到 state.Comment 中或发布到后端。
添加回答
举报