| // src/pages/Forum/CreatePost.jsx |
| import React, { useState } from 'react'; |
| import axios from 'axios'; |
| |
| const CreatePost = ({ userId }) => { |
| const [title, setTitle] = useState(''); |
| const [content, setContent] = useState(''); |
| const [imageUrl, setImageUrl] = useState(''); |
| |
| const handleSubmit = async (e) => { |
| e.preventDefault(); |
| |
| try { |
| const postData = { |
| title, |
| Postcontent: content, |
| }; |
| |
| if (imageUrl.trim()) { |
| postData.imgerrul = imageUrl; |
| } |
| |
| const response = await axios.post( |
| `/echo/forum/posts/${userId}/creatPost`, |
| postData |
| ); |
| |
| if (response.status === 201) { |
| alert('帖子创建成功!'); |
| // 清空表单或跳转页面 |
| setTitle(''); |
| setContent(''); |
| setImageUrl(''); |
| } |
| } catch (error) { |
| console.error('帖子创建失败:', error); |
| 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={imageUrl} |
| onChange={(e) => setImageUrl(e.target.value)} |
| /> |
| </div> |
| <button type="submit">发布</button> |
| </form> |
| </div> |
| ); |
| }; |
| |
| export default CreatePost; |