| // src/pages/Forum/CreatePost.jsx |
| import React, { useState } from 'react'; |
| import axios from 'axios'; |
| |
| const API_BASE = process.env.REACT_APP_API_BASE; |
| |
| const CreatePost = ({ userId }) => { |
| const [title, setTitle] = useState(''); |
| const [content, setContent] = useState(''); |
| const [imgUrl, setImageUrl] = useState(''); |
| const [isAnonymous, setIsAnonymous] = useState(false); |
| |
| const handleSubmit = async (e) => { |
| e.preventDefault(); |
| |
| try { |
| const postData = { |
| title, |
| postContent: content, |
| postType: isAnonymous, |
| }; |
| |
| if (imgUrl.trim()) { |
| postData.imgUrl = imgUrl; |
| } |
| |
| const response = await axios.post( |
| `${API_BASE}/echo/forum/posts/${userId}/createPost`, |
| postData |
| ); |
| |
| |
| if (response.status === 201) { |
| alert('帖子创建成功!'); |
| setTitle(''); |
| setContent(''); |
| setImageUrl(''); |
| setIsAnonymous(false); |
| } |
| } catch (error) { |
| console.error('帖子创建失败:', error.response?.data || error.message); |
| alert('创建失败,请重试'); |
| } |
| }; |
| |
| return ( |
| <div className="create-post"> |
| <h2>创建新帖子</h2> |
| <form onSubmit={handleSubmit}> |
| <div> |
| <label>标题:</label> |
| <input |
| type="text" |
| value={title} |
| onChange={(e) => setTitle(e.target.value)} |
| required |
| /> |
| </div> |
| <div> |
| <label>内容:</label> |
| <textarea |
| value={content} |
| onChange={(e) => setContent(e.target.value)} |
| required |
| /> |
| </div> |
| <div> |
| <label>图片 URL(可选):</label> |
| <input |
| type="text" |
| value={imgUrl} |
| onChange={(e) => setImageUrl(e.target.value)} |
| /> |
| </div> |
| <div> |
| <label> |
| <input |
| type="checkbox" |
| checked={isAnonymous} |
| onChange={(e) => setIsAnonymous(e.target.checked)} |
| /> |
| 匿名发布 |
| </label> |
| </div> |
| <button type="submit">发布</button> |
| </form> |
| </div> |
| ); |
| }; |
| |
| export default CreatePost; |