04 React 样式控制高亮完整案例

本文介绍了一个使用React和useState的简单应用,展示如何创建一个可排序的评论列表,用户可以按时间(新评论)或点赞数进行排序,以及实现删除指定评论的功能。
摘要由CSDN通过智能技术生成
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>
                    {/*判断评论id只有为1的时候,才删除*/}
                    {comment.id === 1 && <button onClick={() => deleteComment(comment.id)}>删除评论</button>}
                </div>
            ))}
        </div>
    );
};

function App() {
    return (
        <>
            <CommentList></CommentList>
        </>
    );
}

export default App;
  • 5
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值