import React, { useState, useEffect } from 'react';
const ChatApp = () => {
const [userMessage, setUserMessage] = useState('');
const [chatLog, setChatLog] = useState([]);
useEffect(() => {
const savedChatLog = JSON.parse(localStorage.getItem('chatLog')) || [];
setChatLog(savedChatLog);
}, []);
const sendMessage = () => {
if (userMessage.trim() === '') return;
const newMessage = { user: true, message: userMessage };
const newLog = [...chatLog, newMessage];
setChatLog(newLog);
localStorage.setItem('chatLog', JSON.stringify(newLog));
generateBotResponse(userMessage);
setUserMessage('');
};
const generateBotResponse = (message) => {
// Здесь может быть логика генерации ответа от ChatGPT или другой системы AI
const botResponse = `Пример ответа от ChatGPT на запрос: ${message}`;
const newMessage = { user: false, message: botResponse };
const newLog = [...chatLog, newMessage];
setChatLog(newLog);
localStorage.setItem('chatLog', JSON.stringify(newLog));
};
const handleKeyPress = (event) => {
if (event.key === 'Enter') {
sendMessage();
}
};
return (
Пример чат-приложения на React.js
{chatLog.map((entry, index) => (
{entry.user ? Вы: : ChatGPT: }
{entry.message}
))}
setUserMessage(e.target.value)}
onKeyPress={handleKeyPress}
style={{ width: '100%', padding: '5px' }}
placeholder="Введите сообщение..."
/>
);
};
export default ChatApp;