整体效果:
项目目录结构:
(可能会觉得有不必要的文件,可以根据自己的想法修改)
CommentBox.js
import {Component} from "react";
import CommentIndex from "../components/comment";
class CommentBox extends Component {
render() {
return (<CommentIndex/>)
}
}
export default CommentBox
index.js
import {Component} from "react";
import CommentList from "./CommentList";
import AddComment from "./AddComment";
class CommentIndex extends Component {
state = {
commentArr: [
{id: 1, author: '小方', content: '今天真的好热啊', date: '2022-7-26'},
{
id: 2,
author: '小小方',
content: '今天真的好热啊',
date: '2022-7-27'
},
{id: 3, author: '小方同学', content: '今天真的好热啊', date: '2022-7-28'}]
}
addCommentInfo=(commentObj)=>{
console.log('父组件',commentObj);
this.setState({
commentArr:[...this.state.commentArr,commentObj]//方法一
// this.state.commentArr.push(commentObj)//方法二
})
}
render() {
return (
<div>
<CommentList data={this.state.commentArr}/>
<AddComment onAddComment={this.addCommentInfo}/>
</div>
)
}
}
export default CommentIndex
CommentList.js
import {Component} from "react";
import Comment from "./Comment";
class CommentList extends Component {
displayCommentList = () => {
return this.props.data.map((item) => {
return (<Comment author={item.author} content={item.content} date={item.date} key={item.id}/>)
})
}
render() {
return (
<div>
<h2>留言列表</h2>
{this.displayCommentList()}
</div>
)
}
}
export default CommentList
Comment.js
import {Component} from "react";
class Comment extends Component {
render() {
return (
<div>
<p>{this.props.author}说:</p>
<p>{this.props.content}</p>
<p className='commentDate'>{this.props.date}</p>
</div>
)
}
}
export default Comment
AddComment.js
import React, {Component} from "react";
class AddComment extends Component {
userRef = React.createRef();
contentRef = React.createRef();
addComment = () => {
const author = this.userRef.current.value;
const content = this.contentRef.current.value
const newComment = {id: new Date().getTime(), author, content, date: new Date().toLocaleDateString()}
this.props.onAddComment(newComment);
}
render() {
return (
<div>
<h2>添加留言</h2>
<p><input type="text" placeholder='请输入姓名:' ref={this.userRef}/></p>
<p><textarea name="" id="" cols="30" rows="10" placeholder='请输入评论内容' ref={this.contentRef}></textarea>
</p>
<p>
<button onClick={this.addComment}>添加留言</button>
</p>
</div>
)
}
}
export default AddComment