聊天机器人组件
用法
要将 Chatbot
组件集成到您的应用程序中,您首先需要导入它
import Chatbot from './path/to/Chatbot';
接下来,在应用程序的组件树中渲染 Chatbot
组件,并提供必要的 props
<Chatbot messages={listMessages} />
listMessages
应该是您要最初显示的消息对象的数组。
组件 Props
Chatbot
组件接受以下 props
名称 | 描述 | 必需 |
---|---|---|
|
聊天机器人将渲染的消息对象的数组。每个消息对象应包含 |
是 |
消息对象结构
messages
数组 prop 中的每个消息对象都应遵循此结构
{
id: number; // Unique identifier for the message
user: string; // "user" for user messages, "chatbot" for chatbot messages
message: string; // The message text
datetime: string; // Timestamp of the message
isTyping?: boolean; // Optional, simulates typing effect for chatbot messages
}
关键组件
示例
以下是使用带有初始消息的 Chatbot
组件的基本示例
const listMessages = [
{
id: 1,
user: 'user',
message: 'Hello, chatbot!',
datetime: '01/01/2024 00:00:00',
},
{
id: 2,
user: 'chatbot',
message: 'Hello! How can I assist you today?',
datetime: '01/01/2024 00:00:00',
},
];
<Chatbot messages={listMessages} />
这将呈现一个聊天界面,其中包含两条初始消息,一条来自用户,一条来自聊天机器人。
组件集成
将 Chatbot
组件集成到现有应用程序中非常简单。确保为其提供必要的 messages
prop 以初始化聊天历史记录。该组件在内部处理用户输入和聊天机器人响应,提供开箱即用的完整聊天界面体验。
如果您已经有负责生成聊天机器人响应的后端应用程序,并且想要将其与 Chatbot
组件集成,以下是一个示例
首先,我们将设置一个新的状态 gettingResponse
,它将指示我们当前是否正在从后端获取响应
const [gettingResponse, setGettingResponse] = useState(false);
然后,我们将定义一个新函数 fetchResponseFromAPI
,它将负责根据用户的消息从后端获取聊天机器人的响应
const fetchResponseFromAPI = async () => {
setGettingResponse(true);
const requestBody = {
message: inputMessage
};
try {
const response = await fetch(`<URI_TO_YOUR_BACKEND_API>`, {
method: 'POST',
headers: {
'accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify(requestBody),
});
const data = await response.json();
setGettingResponse(false);
return data.content;
} catch (error) {
console.error("API call failed:", error);
return "Sorry, something went wrong.";
} finally {
setGettingResponse(false);
}
};
理想情况下,您需要考虑使用框架来管理状态、缓存和 hook,例如 tanstack/react-query ,以及向您的后端 API 调用添加身份验证和授权 |
然后,我们只需要在用户提交消息时调用此函数,检索响应并模拟打字效果:在我们的 handleSubmit
函数中
const chatbotReply = await fetchResponseFromAPI();
simulateTypingEffect(chatbotReply);