import React, { useState, useEffect } from 'react';
import {Button,Input} from "antd";
function TypewriterText({ text, id}) {
const [displayText, setDisplayText] = useState('');
const [index, setIndex] = useState(0);
useEffect(() => {
const timer = setTimeout(() => {
if (index < text.length) {
setDisplayText((prevText) => prevText + text[index]);
setIndex((prevIndex) => prevIndex + 1);
}
}, 100); // 设置打字速度
return () => {
clearTimeout(timer)
};
}, [index, text]);
return <div key={id}>AI:{displayText}</div>;
}
function IntelligentQA() {
const [question, setQuestion] = useState('');
const [botList, setBotList] = useState([]);
const [isTyping, setIsTyping] = useState(false);
const handleQuestionChange = (event) => {
setQuestion(event.target.value);
};
const handleSubmitQuestion = async (e) => {
try {
e.preventDefault();
if (!question.trim()|| isTyping) return;
setIsTyping(true);
setBotList((prevBotList) => [...prevBotList, { text: question, type: 'user' }]);
setTimeout(() => {
const response = 'const response = await askQuestionToAI(question); // 替换成你选择的 AI'
setBotList((prevBotList) => [...prevBotList, { text: response, type: 'ai'}]);
setIsTyping(false); // Typing complete
setQuestion('')
}, 2000);
} catch (error) {
console.error('Error asking question:', error);
}
};
return (
<div>
<Input
value={question}
onChange={handleQuestionChange}
placeholder="请输入你的问题"
/>
<Button onClick={handleSubmitQuestion} loading={isTyping}>发送</Button>
{(botList.map((item, index) => (
<>
{item.type === 'ai' ? (<TypewriterText key={index} id={index} text={item.text} />) : (<div key={index + 3} style={{ color: 'red' }}>user:{item.text}</div>)}
</>
)))}
</div>
);
}
export default IntelligentQA;
react实现AI对话
于 2024-04-23 09:19:51 首次发布