利用React写一个评论列表
时间: 2024-03-17 22:41:28 浏览: 16
好的,以下是一个简单的React评论列表示例代码。请注意,这只是一个基本的模板,您可以根据自己的需求进行修改和调整。
```jsx
import React, { useState } from 'react';
const Comment = ({ author, text }) => (
<div>
<h4>{author}</h4>
<p>{text}</p>
</div>
);
const CommentList = ({ comments }) => (
<div>
{comments.map((comment, i) => (
<Comment key={i} author={comment.author} text={comment.text} />
))}
</div>
);
const CommentSection = () => {
const [comments, setComments] = useState([
{ author: 'Alice', text: 'This is a great post!' },
{ author: 'Bob', text: 'Thanks for sharing!' },
]);
return (
<div>
<h3>Comments</h3>
<CommentList comments={comments} />
</div>
);
};
export default CommentSection;
```
在上面的代码中,我们首先定义了一个`Comment`组件,用于渲染单个评论。然后,我们定义了一个`CommentList`组件,用于渲染所有评论。在`CommentList`中,我们使用`map`函数遍历`comments`数组,并为每个评论创建一个`Comment`组件。
最后,我们定义了一个`CommentSection`组件,使用`useState`hook来管理所有评论的状态,并将`comments`数组作为`props`传递给`CommentList`组件来渲染评论列表。请注意,这里只是添加了一些示例评论,您可以根据自己的需求动态地添加/删除评论。