import React, {useState} from "react";
import styles from "./App.module.css"
const SortType = {
NEWEST: 'NEWEST',
LIKES: 'LIKES'
}
const initialComments = [
{id: 1, username: 'User1', date: '2024-03-24', likes: 10},
{id: 2, username: 'User2', date: '2024-03-23', likes: 5},
{id: 3, username: 'User3', date: '2024-03-22', likes: 8},
{id: 4, username: 'User4', date: '2024-03-21', likes: 3},
{id: 5, username: 'User5', date: '2024-03-20', likes: 12},
{id: 6, username: 'User6', date: '2024-03-19', likes: 7},
{id: 7, username: 'User7', date: '2024-03-18', likes: 15},
{id: 8, username: 'User8', date: '2024-03-17', likes: 2},
{id: 9, username: 'User9', date: '2024-03-16', likes: 9},
{id: 10, username: 'User10', date: '2024-03-15', likes: 6},
];
const CommentList = () => {
const [comments, setComments] = useState(initialComments);
const [sortType, setSortType] = useState(SortType.NEWEST);
const deleteComment = (id) => {
setComments(comments.filter(comment => comment.id !== id));
};
const sortBy = (type) => {
if (type === SortType.NEWEST) {
setSortType(SortType.NEWEST);
setComments([...comments].sort((a, b) => new Date(b.date) - new Date(a.date)));
} else if (type === SortType.LIKES) {
setSortType(SortType.LIKES);
setComments([...comments].sort((a, b) => b.likes - a.likes));
}
};
return (
<div>
<button className={sortType === SortType.NEWEST ? styles.active : ''} onClick={() => sortBy(SortType.NEWEST)}>最新排序</button>
<button className={sortType === SortType.LIKES ? styles.active : ''} onClick={() => sortBy(SortType.LIKES)}>点赞排序</button>
{comments.map(comment => (
<div key={comment.id}>
<p>{comment.username} - {comment.date} - Likes: {comment.likes}</p>
{}
{comment.id === 1 && <button onClick={() => deleteComment(comment.id)}>删除评论</button>}
</div>
))}
</div>
);
};
function App() {
return (
<>
<CommentList></CommentList>
</>
);
}
export default App;