昨天我們做了聊天室UI,雖然可以送出訊息,但只有使用者自己能看到。今天我們要加入一個「假AI回覆」,讓整個聊天室變得像真的在對話。
在送出訊息後,讓系統自動加一則AI回覆:
// src/ChatBox.jsx
import { useState } from "react"
export default function ChatBox(){
const [messages, setMessages] = useState([])
const [input, setInput] = useState("")
const sendMessage = () => {
if(input.trim() === "") return
// 先把使用者訊息加進去
const newMessages = [...messages, {role: "user", text: input}]
setMessages(newMessages)
setInput("")
// 模擬 AI 回覆(假AI)
setTimeout(() => {
setMessages([...newMessages, {role: "ai", text: "這是AI的回覆:我收到了!"}])
}, 500) // 0.5秒後回覆
}
return (
<div className="flex flex-col h-full">
{/* 聊天訊息區 */}
<div className="flex-1 overflow-y-auto space-y-3 p-4 bg-white rounded shadow">
{messages.map((msg, idx) => (
<div
key={idx}
className={`p-2 rounded max-w-xs ${
msg.role === "user"
? "bg-blue-100 ml-auto text-right"
: "bg-gray-200 mr-auto text-left"
}`}
>
{msg.text}
</div>
))}
</div>
{/* 輸入框 */}
<div className="flex mt-4">
<input
value={input}
onChange={(e) => setInput(e.target.value)}
className="flex-1 border rounded-l px-3 py-2"
placeholder="輸入訊息..."
/>
<button
onClick={sendMessage}
className="bg-blue-600 text-white px-4 rounded-r hover:bg-blue-700"
>
送出
</button>
</div>
</div>
)
}
這樣聊天室就有了雙方互動的雛形,即使AI回覆是假的,也能驗證介面與流程。
今天我們完成了「假AI回覆」,讓聊天室變得更像真的。這一步很重要,因為: