React+TailwindCSS聊天机器人:messages内部div无法滚动如何解决?
解决聊天消息容器滚动问题
问题出在消息容器的高度设置和父容器布局逻辑上,调整以下几点即可修复:
- 父容器移除
justify-between,改用flex-col自然布局,避免元素位置冲突 - 将消息容器的
h-full替换为flex-1,让它自动占据屏幕减去标题和输入框后的剩余空间 - 保留
overflow-y-auto开启垂直滚动,justify-end确保新消息始终显示在底部
修改后的代码:
const Chat = () => { return ( <div className="flex flex-col items-center h-screen"> <div className="flex justify-center w-full"> <h1 className="text-3xl font-bold my-5">Golfdommer</h1> </div> <div id="messages" className="flex flex-col w-full flex-1 justify-end overflow-y-auto px-4"> {messages.map((message, index) => { if (message.role === "user") { return <UserMessage key={index} text={message.content} />; } return <BotMessage key={index} text={message.content} />; })} </div> <form onSubmit={handleInputSubmit} className="flex flex-row w-full mb-5 mt-2 px-4" > <textarea className="border-2 rounded-md p-3 w-full mr-1" type="text" value={inputValue} placeholder="Ask me something..." onChange={(e) => setInputValue(e.target.value)} /> <button type="submit" className="ml-1 py-2 px-4 rounded-md bg-green-500"> <PaperAirplaneIcon className="w-6 h-6 text-white" /> </button> </form> </div> ); };
原因说明
原来的h-full会让消息容器高度等于整个屏幕,加上标题和输入框的高度后,整体内容超出屏幕范围,滚动时顶部消息会被标题遮挡。改用flex-1后,消息容器只会占用屏幕剩余可用空间,配合overflow-y-auto就能在消息过多时正常滚动,同时justify-end保证新消息始终固定在底部区域。
内容的提问来源于stack exchange,提问作者bragi
相关产品推荐
相关产品推荐

