'use client' import { useState } from "react" import { useRouter } from "next/navigation" export default function NewsForm({ news, }: { news?: { id?: number title: string content: string type?: string published?: boolean } }) { const router = useRouter() const [formData, setFormData] = useState({ title: news?.title || "", content: news?.content || "", type: news?.type || "news", published: news?.published || false, }) const [loading, setLoading] = useState(false) const [error, setError] = useState("") const handleSubmit = async (e: React.FormEvent) => { e.preventDefault() setLoading(true) setError("") try { const url = news?.id ? `/api/admin/news/${news.id}` : "/api/admin/news" const method = news?.id ? "PUT" : "POST" const res = await fetch(url, { method, headers: { "Content-Type": "application/json" }, body: JSON.stringify(formData), }) if (res.ok) { router.push("/admin/news") } else { setError("保存失败") } } catch (err) { setError("保存失败,请稍后重试") } finally { setLoading(false) } } return (
{error && (
{error}
)}
setFormData({ ...formData, title: e.target.value })} className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500" placeholder="输入新闻标题" />