blob: 9708566199add67f4cf7dd3bef74548a079e9d4f [file] [log] [blame] [edit]
// src/components/Comment.jsx
import React, { useState, useEffect } from 'react';
import {
getCommentsByPostId,
createComment,
deleteComment,
likeComment,
unlikeComment,
} from '../api/comment';
const Comment = ({ postId, currentUser }) => {
const [comments, setComments] = useState([]);
const [newContent, setNewContent] = useState('');
useEffect(() => {
loadComments();
}, [postId]);
const loadComments = async () => {
const data = await getCommentsByPostId(postId);
setComments(data);
};
const handleCreate = async () => {
if (!newContent.trim()) return;
const commentData = {
postid: postId,
userid: currentUser.id,
postCommentcontent: newContent,
commenttime: new Date().toISOString()
};
await createComment(commentData);
setNewContent('');
loadComments();
};
const handleDelete = async (commentid) => {
await deleteComment(commentid);
loadComments();
};
const handleLike = async (commentid) => {
await likeComment(commentid);
loadComments();
};
const handleUnlike = async (commentid) => {
await unlikeComment(commentid);
loadComments();
};
return (
<div>
<h4 className="font-semibold text-gray-700 mb-2">评论</h4>
<div className="mb-2">
<textarea
value={newContent}
onChange={(e) => setNewContent(e.target.value)}
placeholder="写下你的评论..."
className="w-full border rounded p-2"
/>
<button
onClick={handleCreate}
className="mt-2 bg-blue-500 text-white px-3 py-1 rounded hover:bg-blue-600"
>
发布评论
</button>
</div>
<div className="space-y-2 mt-4">
{comments.map((comment) => (
<div key={comment.commentid} className="border rounded p-2">
<div className="text-sm text-gray-800 font-medium">用户ID:{comment.userid}</div>
<div className="text-gray-700">{comment.postCommentcontent}</div>
<div className="text-xs text-gray-500 mt-1">
{comment.commenttime || '暂无时间'} | 👍 {comment.likes}
</div>
<div className="flex gap-2 mt-1 text-sm">
<button onClick={() => handleLike(comment.commentid)} className="text-blue-500 hover:underline">点赞</button>
<button onClick={() => handleUnlike(comment.commentid)} className="text-yellow-500 hover:underline">取消点赞</button>
{comment.userid === currentUser.id && (
<button onClick={() => handleDelete(comment.commentid)} className="text-red-500 hover:underline">删除</button>
)}
</div>
</div>
))}
</div>
</div>
);
};
export default Comment;