react实现AI对话

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;

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值