blob: a03a836385379b1fa1750c5b8a4a0aba5b539fd9 [file] [log] [blame]
Krishyae71688a2025-04-10 21:25:17 +08001// src/pages/Forum/CreatePost.jsx
2import React, { useState } from 'react';
3import axios from 'axios';
4
Krishya7ec1dd02025-04-19 15:29:03 +08005const API_BASE = process.env.REACT_APP_API_BASE;
6
Krishyae71688a2025-04-10 21:25:17 +08007const CreatePost = ({ userId }) => {
8 const [title, setTitle] = useState('');
9 const [content, setContent] = useState('');
Krishya7ec1dd02025-04-19 15:29:03 +080010 const [imgUrl, setImageUrl] = useState('');
11 const [isAnonymous, setIsAnonymous] = useState(false);
Krishyae71688a2025-04-10 21:25:17 +080012
13 const handleSubmit = async (e) => {
14 e.preventDefault();
15
16 try {
17 const postData = {
18 title,
Krishya7ec1dd02025-04-19 15:29:03 +080019 postContent: content,
20 postType: isAnonymous,
Krishyae71688a2025-04-10 21:25:17 +080021 };
22
Krishya7ec1dd02025-04-19 15:29:03 +080023 if (imgUrl.trim()) {
24 postData.imgUrl = imgUrl;
Krishyae71688a2025-04-10 21:25:17 +080025 }
26
27 const response = await axios.post(
Krishya7ec1dd02025-04-19 15:29:03 +080028 `${API_BASE}/echo/forum/posts/${userId}/createPost`,
Krishyae71688a2025-04-10 21:25:17 +080029 postData
30 );
Krishya7ec1dd02025-04-19 15:29:03 +080031
Krishyae71688a2025-04-10 21:25:17 +080032
33 if (response.status === 201) {
34 alert('帖子创建成功!');
Krishyae71688a2025-04-10 21:25:17 +080035 setTitle('');
36 setContent('');
37 setImageUrl('');
Krishya7ec1dd02025-04-19 15:29:03 +080038 setIsAnonymous(false);
Krishyae71688a2025-04-10 21:25:17 +080039 }
40 } catch (error) {
Krishya7ec1dd02025-04-19 15:29:03 +080041 console.error('帖子创建失败:', error.response?.data || error.message);
Krishyae71688a2025-04-10 21:25:17 +080042 alert('创建失败,请重试');
Krishya7ec1dd02025-04-19 15:29:03 +080043 }
Krishyae71688a2025-04-10 21:25:17 +080044 };
45
46 return (
47 <div className="create-post">
48 <h2>创建新帖子</h2>
49 <form onSubmit={handleSubmit}>
50 <div>
51 <label>标题:</label>
52 <input
53 type="text"
54 value={title}
55 onChange={(e) => setTitle(e.target.value)}
56 required
57 />
58 </div>
59 <div>
60 <label>内容:</label>
61 <textarea
62 value={content}
63 onChange={(e) => setContent(e.target.value)}
64 required
65 />
66 </div>
67 <div>
68 <label>图片 URL(可选):</label>
69 <input
70 type="text"
Krishya7ec1dd02025-04-19 15:29:03 +080071 value={imgUrl}
Krishyae71688a2025-04-10 21:25:17 +080072 onChange={(e) => setImageUrl(e.target.value)}
73 />
74 </div>
Krishya7ec1dd02025-04-19 15:29:03 +080075 <div>
76 <label>
77 <input
78 type="checkbox"
79 checked={isAnonymous}
80 onChange={(e) => setIsAnonymous(e.target.checked)}
81 />
82 匿名发布
83 </label>
84 </div>
Krishyae71688a2025-04-10 21:25:17 +080085 <button type="submit">发布</button>
86 </form>
87 </div>
88 );
89};
90
Krishya7ec1dd02025-04-19 15:29:03 +080091export default CreatePost;