import React, { useState, useRef, useEffect } from 'react'; import { Send, Bot, User } from 'lucide-react'; interface Message { id: string; content: string; role: 'user' | 'assistant'; timestamp: Date; } export const ChatInterface: React.FC = () => { const [messages, setMessages] = useState([ { id: '1', content: '你好!我是AI助手,有什么可以帮助您的吗?', role: 'assistant', timestamp: new Date() } ]); const [inputValue, setInputValue] = useState(''); const [isLoading, setIsLoading] = useState(false); const messagesEndRef = useRef(null); const inputRef = useRef(null); // 自动滚动到最新消息 const scrollToBottom = () => { messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' }); }; useEffect(() => { scrollToBottom(); }, [messages]); // 发送消息 const handleSend = async () => { if (!inputValue.trim() || isLoading) return; const userMessage: Message = { id: Date.now().toString(), content: inputValue.trim(), role: 'user', timestamp: new Date() }; setMessages(prev => [...prev, userMessage]); setInputValue(''); setIsLoading(true); // 模拟AI回复 setTimeout(() => { const aiMessage: Message = { id: (Date.now() + 1).toString(), content: `我收到了您的消息:"${userMessage.content}"。这里是我的回复,您还有其他问题吗?`, role: 'assistant', timestamp: new Date() }; setMessages(prev => [...prev, aiMessage]); setIsLoading(false); }, 1000); }; // 处理键盘事件 const handleKeyDown = (e: React.KeyboardEvent) => { if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); handleSend(); } }; // 格式化时间 const formatTime = (date: Date) => { return date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' }); }; return (
{/* 头部 */}

智能工作台

在线 · 随时为您服务

{/* 对话列表区域 */}
{messages.map((message) => (
{message.role === 'assistant' && (
)}
{message.content}
{formatTime(message.timestamp)}
{message.role === 'user' && (
)}
))} {/* 加载状态 */} {isLoading && (
)}
{/* 输入框区域 */}