React+Django Channels聊天应用:实现不同用户消息异色显示
实现聊天消息的用户区分颜色方案
核心思路
别直接把JSX存在state里,改用存储消息数据对象的方式更灵活,然后通过判断消息发送者是否为当前用户,分配不同的样式类或动态颜色。
步骤1:调整State存储结构
把原来存JSX的state改成存消息数据:
const [messages, setMessages] = useState([]);
步骤2:处理接收消息的逻辑
确保后端返回的消息包含发送者用户名(比如data.sender),判断是否为当前用户后存入state:
chatSocket.onmessage = function(e) { if (ran) { const data = JSON.parse(e.data); const isCurrentUser = data.sender === currentUser[0]?.username; setMessages(old => [...old, { message: data.message, sender: data.sender, isCurrentUser: isCurrentUser }]); } };
步骤3:优化发送消息的逻辑
发送消息时直接把自己的消息加入state(不用等服务器返回,提升体验):
function theone(e) { e.preventDefault(); if (!myInput.trim()) return; // 过滤空消息 // 先把自己的消息加入state const newMsg = { message: myInput, sender: currentUser[0]?.username, isCurrentUser: true }; setMessages(old => [...old, newMsg]); // 再发送给服务器 chatSocket.send(JSON.stringify({ 'message': myInput })); setMyInput(''); // 和input的value对应,修正你之前的setMyInput2笔误 }
步骤4:渲染消息列表
用map循环渲染消息,根据isCurrentUser分配样式:
<div className="messages-container"> {messages.map((msg, index) => ( <p key={index} {/* 最好用后端返回的消息ID当key,避免渲染问题 */} className={`message ${msg.isCurrentUser ? 'current-user' : 'other-user'}`} style={!msg.isCurrentUser ? { backgroundColor: getUserColor(msg.sender) } : {}} > {msg.message} </p> ))} </div>
步骤5:编写基础样式
给当前用户和其他用户设置基础样式:
.message { padding: 8px 12px; border-radius: 4px; margin: 4px 0; max-width: 70%; } .current-user { background-color: red; color: white; margin-left: auto; /* 自己的消息右对齐 */ } .other-user { margin-right: auto; /* 其他用户消息左对齐 */ }
步骤6:给不同其他用户分配独特颜色
写个简单的函数,根据用户名生成固定的独特颜色:
function getUserColor(username) { // 通过用户名哈希生成HSL颜色 let hash = 0; for (let i = 0; i < username.length; i++) { hash = username.charCodeAt(i) + ((hash << 5) - hash); } // 生成柔和的色调 return `hsl(${hash % 360}, 70%, 80%)`; }
注意事项
- 确保后端返回的消息必须包含发送者用户名,否则无法区分用户
- 不要用
index作为key,优先使用后端生成的消息唯一ID - 输入框的清空逻辑要和
value绑定的state一致(比如你的myInput对应setMyInput)
内容的提问来源于stack exchange,提问作者zequuee1
相关产品推荐
相关产品推荐

