React 18函数式组件中使用WebSocket完整代码
·
在 React 18 函数式组件 中使用 WebSocket,主要思路是:
- 在组件内(或自定义 Hook 中)创建 WebSocket 连接
- 使用 useEffect管理 WebSocket 的生命周期(创建、销毁)
- 使用 useState或其它状态管理方式存储收到的数据和连接状态
- 通过 WebSocket 的 send()方法向服务端发送消息
下面是一个完整的、可直接运行的示例,展示如何在 React 18 函数式组件中集成和使用 WebSocket。
✅ 示例:React 18 函数式组件中使用 WebSocket
🧩 功能描述
建立与 WebSocket 服务器的连接(这里以 ws://echo.websocket.org为例,它是一个测试用的公共 WebSocket 服务,会返回你发送的消息)。
输入框中输入内容,点击发送按钮将消息发送给服务器。
接收服务器返回的消息并显示在页面上。
显示连接状态(已连接 / 已断开)。
1. 基本组件代码(App.jsx 或 App.tsx)
import React, { useState, useEffect, useRef } from 'react';
function App() {
const [messages, setMessages] = useState([]); // 存储所有消息
const [inputValue, setInputValue] = useState(''); // 输入框内容
const [isConnected, setIsConnected] = useState(false); // WebSocket 是否已连接
const ws = useRef(null); // 保存 WebSocket 实例(用 ref 避免重复创建)
// WebSocket 服务器地址(可替换成你自己的服务地址,如 wss://your-api.com/ws)
const WS_URL = 'wss://echo.websocket.org'; // 注意:这是一个公共测试服务
useEffect(() => {
// 创建 WebSocket 连接
ws.current = new WebSocket(WS_URL);
// 连接成功时
ws.current.onopen = () => {
console.log('✅ WebSocket 已连接');
setIsConnected(true);
addMessage('系统:WebSocket 连接已建立');
};
// 接收到消息时
ws.current.onmessage = (event) => {
console.log('📥 收到消息:', event.data);
addMessage(`📥 服务器:${event.data}`);
};
// 连接关闭时
ws.current.onclose = (event) => {
console.log('❌ WebSocket 已关闭', event.code, event.reason);
setIsConnected(false);
addMessage('系统:WebSocket 连接已关闭');
};
// 发生错误时
ws.current.onerror = (error) => {
console.error('⚠️ WebSocket 错误:', error);
addMessage('系统:WebSocket 出现错误');
};
// 组件卸载时关闭 WebSocket 连接,防止内存泄漏
return () => {
if (ws.current) {
ws.current.close();
console.log('🔌 清理 WebSocket 连接');
}
};
}, []); // 空依赖数组,只在组件挂载时执行一次
// 辅助函数:添加消息到消息列表
const addMessage = (text) => {
setMessages((prev) => [...prev, { id: Date.now(), text }]);
};
// 发送消息给服务器
const sendMessage = () => {
if (!ws.current || ws.current.readyState !== WebSocket.OPEN) {
alert('⚠️ WebSocket 未连接,请稍后再试');
return;
}
const message = inputValue.trim();
if (!message) return;
// 发送到服务器
ws.current.send(message);
addMessage(`📤 我:${message}`);
// 清空输入框
setInputValue('');
};
// 支持回车发送
const handleKeyPress = (e) => {
if (e.key === 'Enter') {
sendMessage();
}
};
return (
<div style={{ maxWidth: '600px', margin: '50px auto', padding: '20px', fontFamily: 'Arial' }}>
<h2>React 18 + WebSocket 示例</h2>
<p><strong>状态:</strong>{isConnected ? '🟢 已连接' : '🔴 未连接'}</p>
{/* 消息历史 */}
<div style={{
border: '1px solid #ccc',
borderRadius: '5px',
padding: '10px',
height: '300px',
overflowY: 'auto',
marginBottom: '10px'
}}>
{messages.map((msg) => (
<div key={msg.id} style={{ marginBottom: '5px', wordBreak: 'break-word' }}>
{msg.text}
</div>
))}
</div>
{/* 输入区 */}
<div>
<input
type="text"
value={inputValue}
onChange={(e) => setInputValue(e.target.value)}
onKeyPress={handleKeyPress}
placeholder="输入消息,按回车或点击发送"
disabled={!isConnected}
style={{
padding: '8px',
width: '70%',
marginRight: '10px',
borderRadius: '4px',
border: '1px solid #ccc'
}}
/>
<button
onClick={sendMessage}
disabled={!isConnected || !inputValue.trim()}
style={{
padding: '8px 16px',
borderRadius: '4px',
border: 'none',
backgroundColor: '#007bff',
color: 'white',
cursor: 'pointer'
}}
>
发送
</button>
</div>
</div>
);
}
export default App;
🔍 代码要点解析
|
部分 |
说明 |
|---|---|
|
|
使用 |
|
|
在组件挂载时创建连接,卸载时关闭连接,防止内存泄漏 |
|
|
监听 WebSocket 的各种事件,更新 UI 和状态 |
|
|
手动向服务器发送消息,先判断连接是否打开 |
|
消息渲染 |
使用 |
|
输入 & 发送 |
支持按钮点击发送,也支持回车键快捷发送 |
更多推荐



所有评论(0)