翻譯頁面今天要做到:
/*TranslationTool.jsx*/
import { useState } from "react"
export default function TranslationTool() {
const [input, setInput] = useState("")
const [output, setOutput] = useState("")
const [history, setHistory] = useState([])
const [direction, setDirection] = useState("en2zh")
const handleTranslate = () => {
if (!input.trim()) return
// 模擬翻譯邏輯
let fakeResult = ""
if (direction === "en2zh") {
fakeResult = `(中譯)${input} → 你好,這是一個假翻譯`
} else {
fakeResult = `(英譯)${input} → Hello, this is a fake translation`
}
setOutput(fakeResult)
const newRecord = {
id: Date.now(),
from: input,
to: fakeResult,
type: direction,
}
setHistory([newRecord, ...history])
setInput("")
}
const handleDelete = (id) => {
setHistory(history.filter((item) => item.id !== id))
}
return (
<div className="space-y-6">
{/* 輸入區 */}
<div className="bg-white p-4 rounded shadow space-y-3">
<h2 className="text-lg font-semibold">文字翻譯工具</h2>
<div className="flex space-x-2">
<select
value={direction}
onChange={(e) => setDirection(e.target.value)}
className="border px-2 py-1 rounded"
>
<option value="en2zh">英文 → 中文</option>
<option value="zh2en">中文 → 英文</option>
</select>
<input
value={input}
onChange={(e) => setInput(e.target.value)}
placeholder="輸入要翻譯的文字..."
className="flex-1 border px-3 py-2 rounded"
/>
<button
onClick={handleTranslate}
className="bg-blue-600 text-white px-4 py-2 rounded hover:bg-blue-700"
>
翻譯
</button>
</div>
{/* 翻譯結果 */}
{output && (
<div className="mt-4 bg-gray-100 p-3 rounded">
<p className="text-gray-700 font-medium">翻譯結果:</p>
<p>{output}</p>
</div>
)}
</div>
{/* 翻譯紀錄 */}
<div className="bg-white p-4 rounded shadow">
<h3 className="font-semibold mb-2">翻譯紀錄</h3>
{history.length === 0 ? (
<p className="text-gray-500 text-sm">目前沒有紀錄。</p>
) : (
<ul className="space-y-2">
{history.map((item) => (
<li
key={item.id}
className="flex justify-between bg-gray-50 p-2 rounded border"
>
<div>
<p className="text-sm text-gray-600">
<strong>原文:</strong> {item.from}
</p>
<p className="text-sm text-gray-800">
<strong>譯文:</strong> {item.to}
</p>
</div>
<button
onClick={() => handleDelete(item.id)}
className="text-red-600 hover:text-red-800 text-sm"
>
刪除
</button>
</li>
))}
</ul>
)}
</div>
</div>
)
}