07 React 添加列表

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;
  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
这是一个简单的React代办列表,包括添加、删除和完成任务的功能: ```javascript import React, { useState } from 'react'; function TodoList() { const [todos, setTodos] = useState([]); const [newTodo, setNewTodo] = useState(''); const handleNewTodoChange = (event) => { setNewTodo(event.target.value); }; const handleAddTodo = () => { if (newTodo !== '') { setTodos([...todos, { text: newTodo, completed: false }]); setNewTodo(''); } }; const handleDeleteTodo = (index) => { const newTodos = [...todos]; newTodos.splice(index, 1); setTodos(newTodos); }; const handleCompleteTodo = (index) => { const newTodos = [...todos]; newTodos[index].completed = !newTodos[index].completed; setTodos(newTodos); }; return ( <div> <h1>Todo List</h1> <input type="text" value={newTodo} onChange={handleNewTodoChange} /> <button onClick={handleAddTodo}>Add</button> <ul> {todos.map((todo, index) => ( <li key={index}> <span style={{ textDecoration: todo.completed ? 'line-through' : 'none' }}> {todo.text} </span> <button onClick={() => handleDeleteTodo(index)}>Delete</button> <button onClick={() => handleCompleteTodo(index)}> {todo.completed ? 'Undo' : 'Complete'} </button> </li> ))} </ul> </div> ); } export default TodoList; ``` 在这个示例中,我们使用了React的Hooks来管理状态。`useState`函数允许我们在函数组件中使用状态,并通过`setTodos`和`setNewTodo`来更新它们。 在页面上,我们有一个文本框和一个“添加”按钮,可以将新的任务添加列表中。我们还有一个`ul`元素,用于呈现任务列表。每个任务都有一个删除按钮和一个完成按钮,可以将任务标记为已完成或未完成。完成的任务将带有删除线。 我们使用`map`函数来遍历任务列表,并为每个任务呈现一个`li`元素。我们还使用`key`属性来确保React可以更快地重建列表。 总的来说,这是一个简单的React代办列表,可以轻松扩展和自定义,以适应您的需要。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值