07 React 添加列表

js 复制代码
import React, {useState} from "react";
import styles from "./App.module.css"

// 枚举定义排序方式
const SortType = {
    NEWEST: 'NEWEST',
    LIKES: 'LIKES'
}
const CommentForm = ({onAddComment}) => {
    const [newCommentText, setNewCommentText] = useState('');

    const handleAddComment = () => {
        if (newCommentText.trim() !== '') {
            onAddComment(newCommentText);
            setNewCommentText('');
        }
    };

    return (
        <div>
            <input
                type="text"
                value={newCommentText}
                onChange={(e) => setNewCommentText(e.target.value)}
                placeholder="输入你的评论"
            />
            <button onClick={handleAddComment}>提交评论</button>
        </div>
    );
};

const CommentList = ({initialComments}) => {
    const [comments, setComments] = useState(initialComments);
    const [sortType, setSortType] = useState(SortType.NEWEST);

    const getCurrentDate = () => {
        const currentDate = new Date();

        const year = currentDate.getFullYear();
        const month = String(currentDate.getMonth() + 1).padStart(2, '0');
        const day = String(currentDate.getDate()).padStart(2, '0');
        const hours = String(currentDate.getHours()).padStart(2, '0');
        const minutes = String(currentDate.getMinutes()).padStart(2, '0');
        const seconds = String(currentDate.getSeconds()).padStart(2, '0');

        const formattedDateTime = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
        return formattedDateTime
    }

    const addComment = (text) => {
        const newComment = {
            id: comments.length + 1,
            username: 'New User', // 你可能需要添加用户输入用户名的逻辑
            date: getCurrentDate(), // 当前日期
            likes: 0, // 新评论的点赞数
            text: text // 新评论的内容
        };

        refreshComments(sortType, [...comments, newComment])
    };

    // 删除评论
    const deleteComment = (id) => {
        setComments(comments.filter(comment => comment.id !== id));
    };

    // 排序
    const sortBy = (type) => {
        refreshComments(type, comments)
    };

    const refreshComments = (type, comments) => {
        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>
            <CommentForm onAddComment={addComment}/>

            <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} {comment.text}</p>
                    {/*判断评论id只有为1的时候,才删除*/}
                    {comment.id === 1 && <button onClick={() => deleteComment(comment.id)}>删除评论</button>}
                </div>
            ))}
        </div>
    )
};

function App() {
    const getRandomDate = () => {
        const year = 2023;
        const month = Math.floor(1 + Math.random() * 5); // March
        const day = Math.floor(1 + Math.random() * 10);
        const hour = Math.floor(Math.random() * 24); // Random hour between 0 and 23
        const minute = Math.floor(Math.random() * 60); // Random minute between 0 and 59
        const second = Math.floor(Math.random() * 60); // Random second between 0 and 59
        const content = `${year}-${
            month.toString().padStart(2, '0')
        }-${
            day.toString().padStart(2, '0')
        } ${
            hour.toString().padStart(2, '0')
        }:${
            minute.toString().padStart(2, '0')
        }:${
            second.toString().padStart(2, '0')
        }`;
        console.log(content)
        return content
    };

    const initialComments = [
        {id: 1, username: 'User1', date: getRandomDate(), likes: 10, text: '这是一个示例评论。'},
        {id: 2, username: 'User2', date: getRandomDate(), likes: 5, text: '这也是一个示例评论。'},
        {id: 3, username: 'User3', date: getRandomDate(), likes: 8, text: '这是第三个示例评论。'},
        {id: 4, username: 'User4', date: getRandomDate(), likes: 3, text: '这是第四个示例评论。'},
        {id: 5, username: 'User5', date: getRandomDate(), likes: 12, text: '这是第五个示例评论。'},
        {id: 6, username: 'User6', date: getRandomDate(), likes: 7, text: '这是第六个示例评论。'},
        {id: 7, username: 'User7', date: getRandomDate(), likes: 15, text: '这是第七个示例评论。'},
        {id: 8, username: 'User8', date: getRandomDate(), likes: 2, text: '这是第八个示例评论。'},
        {id: 9, username: 'User9', date: getRandomDate(), likes: 9, text: '这是第九个示例评论。'},
        {id: 10, username: 'User10', date: getRandomDate(), likes: 6, text: '这是第十个示例评论。'}
    ];


    return (
        <>
            <CommentList initialComments={initialComments}/>
        </>
    );
}

export default App;
相关推荐
袁煦丞9 分钟前
2025.8.18实验室【代码跑酷指南】Jupyter Notebook程序员的魔法本:cpolar内网穿透实验室第622个成功挑战
前端·程序员·远程工作
Joker Zxc13 分钟前
【前端基础】flex布局中使用`justify-content`后,最后一行的布局问题
前端·css
无奈何杨16 分钟前
风控系统事件分析中心,关联关系、排行、时间分布
前端·后端
Moment22 分钟前
nginx 如何配置防止慢速攻击 🤔🤔🤔
前端·后端·nginx
晓得迷路了27 分钟前
栗子前端技术周刊第 94 期 - React Native 0.81、jQuery 4.0.0 RC1、Bun v1.2.20...
前端·javascript·react.js
江城开朗的豌豆28 分钟前
React Native 实战心得
javascript
前端小巷子29 分钟前
Vue 自定义指令
前端·vue.js·面试
玲小珑35 分钟前
Next.js 教程系列(二十七)React Server Components (RSC) 与未来趋势
前端·next.js
Mike_jia35 分钟前
UptimeRobot API状态监控:零成本打造企业级业务健康看板
前端
江城开朗的豌豆36 分钟前
React状态更新踩坑记:我是这样优雅修改参数的
前端·javascript·react.js