程式化控制 (ChatbotRef)
透過 React ref 從外部操作聊天室。最常見的用法是程式化填入輸入框文字,
例如點擊頁面上的快捷按鈕自動帶入問題。
程式化控制
透過 ref 取得 ChatbotRef,可以從外部操作聊天室:呼叫 setInputValue 填入文字、透過 serviceContext 存取對話狀態。
快速填入
自訂文字
載入中…
程式範例
import { useRef } from "react";
import { Chatbot, ChatbotRef } from "@asgard-js/react";
export function App() {
const chatbotRef = useRef<ChatbotRef>(null);
return (
<>
<button onClick={() => chatbotRef.current?.setInputValue?.("你好")}>
快速填入
</button>
<Chatbot
ref={chatbotRef}
title="我的聊天室"
config={{ botProviderEndpoint: "..." }}
customChannelId="my-channel"
/>
</>
);
}
ChatbotRef
| 欄位 | 型別 | 說明 |
|---|---|---|
setInputValue | (value: string) => void | 程式化設定輸入框文字 |
serviceContext | AsgardServiceContextValue | 存取完整的 service context(messages、sendMessage 等) |
透過 serviceContext 你可以讀取 messages(所有對話訊息)、
呼叫 sendMessage / resetChannel / closeChannel,實現完全的
程式化控制。