如何在react-chat-elements的MessageList组件旁添加Div盒子
问题:给react-chat-elements的MessageList每条消息添加侧边自定义Div盒子
我用react-chat-elements库的MessageList组件做了个简单聊天界面,代码如下:
import { MessageList } from "react-chat-elements" import "react-chat-elements/dist/main.css"; import "./style.css"; //.width400 {width: 400px;} function child() { // 希望这个Div高度和对应消息的高度一致 return ( <div style={{ "width": "7px", "height": "20px", "border": "1px solid black", "background-color": "red", "position": "relative", "display": "flex" }}></div> ); } export function App() { return ( <div> <MessageList className='message-list width400' lockable={true} toBottomHeight={'100%'} dataSource={[ { position: "left", type: "text", title: "Kursat", text: "This is a long message that should have a long element near it. This is a long message that should have a long element near it", }, { position: "right", type: "text", title: "Emre", text: "That's short", }, ]} children={[child(), child()]} isShowChild={true} /> </div> ); }
我想实现的效果是每条消息旁边都有一个自定义的Div盒子,但尝试给MessageList添加children和isShowChild属性后,没达到预期效果。
解决方案
MessageList的children属性并非用来给单条消息绑定附属元素,正确做法是自定义消息组件,通过dataSource的component字段注入自定义内容:
import { Message, MessageList } from "react-chat-elements" import "react-chat-elements/dist/main.css"; import "./style.css"; // 自定义带侧边条的消息组件 function CustomMessage(props) { const { position, title, text } = props; return ( <div style={{ display: 'flex', alignItems: 'flex-start', gap: '8px' }}> {/* 根据消息位置决定侧边条摆放方向 */} {position === 'left' && ( <div style={{ width: '7px', backgroundColor: 'red', border: '1px solid black', alignSelf: 'stretch' }}></div> )} <Message position={position} type="text" title={title} text={text} /> {position === 'right' && ( <div style={{ width: '7px', backgroundColor: 'red', border: '1px solid black', alignSelf: 'stretch' }}></div> )} </div> ); } export function App() { return ( <div> <MessageList className='message-list width400' lockable={true} toBottomHeight={'100%'} dataSource={[ { position: "left", component: <CustomMessage position="left" title="Kursat" text="This is a long message that should have a long element near it. This is a long message that should have a long element near it" /> }, { position: "right", component: <CustomMessage position="right" title="Emre" text="That's short" /> }, ]} /> </div> ); }
关键说明
- 用
alignSelf: 'stretch'让侧边Div高度自动匹配消息容器,无需固定高度值 - 根据消息的
position(left/right)控制侧边条位置,保证布局逻辑正确 - 放弃原
children和isShowChild属性,它们的设计用途并非给单条消息添加附属元素
内容的提问来源于stack exchange,提问作者user2401856
相关产品推荐
相关产品推荐

