iT邦幫忙

2025 iThome 鐵人賽

DAY 15
0
生成式 AI

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

30天用React打造AI工具箱 Day15

  • 分享至 

  • xImage
  •  

30天用React打造AI工具箱 Day15

第一步:打造簡單的Chat介面

目前為止我們已經有了骨架版面(Day12)、頁籤切換(Day13),也寫過TodoApp作為練習。今天要正式開始做AI工具箱的第一個小工具:Chat介面

功能

  • 上方:顯示對話訊息列表
  • 下方:輸入框與送出按鈕
  • 點送出後,訊息會新增到對話區

程式碼

import { useState } from "react"

export default function ChatBox(){
  const [messages,setMessages] = useState([
    { id:1, role:"bot", text:"哈囉!我是AI助手,有什麼可以幫你?" }
  ])
  const [input,setInput] = useState("")

  const sendMessage=(e)=>{
    e.preventDefault()
    const text=input.trim()
    if(!text) return
    setMessages(prev=>[
      ...prev,
      { id:Date.now(), role:"user", text }
    ])
    setInput("")
  }

  return (
    <div className="flex flex-col h-full border rounded bg-white">
      {/* 對話區 */}
      <div className="flex-1 overflow-y-auto p-4 space-y-3">
        {messages.map(msg=>(
          <div
            key={msg.id}
            className={`p-3 rounded-lg max-w-xs ${
              msg.role==="user"
                ? "ml-auto bg-blue-600 text-white"
                : "bg-gray-200 text-gray-800"
            }`}
          >
            {msg.text}
          </div>
        ))}
      </div>

      {/* 輸入框 */}
      <form onSubmit={sendMessage} className="flex border-t">
        <input
          className="flex-1 px-3 py-2 outline-none"
          placeholder="輸入訊息..."
          value={input}
          onChange={e=>setInput(e.target.value)}
        />
        <button className="px-4 bg-blue-600 text-white">送出</button>
      </form>
    </div>
  )
}

畫面

https://ithelp.ithome.com.tw/upload/images/20250929/20168638ni1LLbGxch.png

今天先做出這個畫面與chat的開場白,之後預計會在這邊接上AI Agent/LLM對話功能。


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

尚未有邦友留言

立即登入留言