You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

93 lines
2.9 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

import React, { useState, useEffect } from 'react';
import styles from './styles.module.css';
export default function Comment({ docId }) {
const [comments, setComments] = useState([]);
const [newComment, setNewComment] = useState('');
const [isOpen, setIsOpen] = useState(false);
useEffect(() => {
// 从localStorage中读取评论
const savedComments = JSON.parse(localStorage.getItem(`docComments_${docId}`) || '[]');
setComments(savedComments);
}, [docId]);
const handleAddComment = () => {
if (!newComment.trim()) return;
const comment = {
id: Date.now(),
text: newComment,
timestamp: new Date().toLocaleString(),
author: '用户' // 这里可以替换为实际的用户名
};
const updatedComments = [...comments, comment];
setComments(updatedComments);
localStorage.setItem(`docComments_${docId}`, JSON.stringify(updatedComments));
setNewComment('');
};
const handleDeleteComment = (commentId) => {
const updatedComments = comments.filter(comment => comment.id !== commentId);
setComments(updatedComments);
localStorage.setItem(`docComments_${docId}`, JSON.stringify(updatedComments));
};
return (
<div className={styles.commentContainer}>
<button
onClick={() => setIsOpen(!isOpen)}
className={styles.commentButton}
aria-label="评论"
type="button"
>
<svg
viewBox="0 0 24 24"
width="16"
height="16"
stroke="currentColor"
strokeWidth="2"
fill="none"
strokeLinecap="round"
strokeLinejoin="round"
>
<path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z" />
</svg>
</button>
{isOpen && (
<div className={styles.commentPanel}>
<div className={styles.commentList}>
{comments.map(comment => (
<div key={comment.id} className={styles.commentItem}>
<div className={styles.commentHeader}>
<span className={styles.commentAuthor}>{comment.author}</span>
<span className={styles.commentTime}>{comment.timestamp}</span>
<button
onClick={() => handleDeleteComment(comment.id)}
className={styles.deleteButton}
>
×
</button>
</div>
<div className={styles.commentText}>{comment.text}</div>
</div>
))}
</div>
<div className={styles.commentInput}>
<textarea
value={newComment}
onChange={(e) => setNewComment(e.target.value)}
placeholder="添加评论..."
rows={3}
/>
<button onClick={handleAddComment} className={styles.submitButton}>
发表评论
</button>
</div>
</div>
)}
</div>
);
}