iT邦幫忙

2025 iThome 鐵人賽

DAY 17
0
生成式 AI

30天用React打造AI工具箱系列 第 17

30天用React打造AI工具箱 Day17

  • 分享至 

  • xImage
  •  

30天用React打造AI工具箱 Day17

假AI回覆:讓聊天室開始互動

昨天我們做了聊天室UI,雖然可以送出訊息,但只有使用者自己能看到。今天我們要加入一個「假AI回覆」,讓整個聊天室變得像真的在對話。

第一步:修改ChatBox.jsx

在送出訊息後,讓系統自動加一則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>
  )
}

執行效果:

  1. 先輸入一段文字,例如「你好」。
  2. 按下「送出」,畫面會先顯示「使用者」的訊息。
  3. 0.5秒後,畫面會多一則來自「AI」的訊息:「這是AI的回覆:我收到了!」

這樣聊天室就有了雙方互動的雛形,即使AI回覆是假的,也能驗證介面與流程。

小結

今天我們完成了「假AI回覆」,讓聊天室變得更像真的。這一步很重要,因為:

  • 它讓我們檢查UI能不能正確顯示雙方訊息。
  • 它建立了「送出訊息 → 處理 → 加入AI訊息」的程式架構。
  • 未來只要把假AI改成呼叫API,就能真正接入AI聊天了。

上一篇
30天用React打造AI工具箱 Day16
系列文
30天用React打造AI工具箱17
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言