use stick to bottom
1.0.0
useStickToBottom
设计时考虑了人工智能聊天机器人,为 StackBlitz 的
bolt.new
提供支持
一个轻量级的零依赖React hook + 组件,可自动粘贴到容器底部并平滑地对内容进行动画处理,以在添加新内容时保持其在屏幕上的视觉位置。
overflow-anchor
浏览器级 CSS 支持。isAtBottom
并以编程方式滚动到底部。ResizeObserver
API 来检测内容何时调整大小。scrollToBottom
返回一个Promise<boolean>
一旦滚动成功,它将解析为true
,如果滚动被取消,则解析为false
。<StickToBottom>
组件 import { StickToBottom , useStickToBottomContext } from 'use-stick-to-bottom' ;
function Chat ( ) {
return (
< StickToBottom className = "h-[50vh] relative" resize = "smooth" initial = "smooth" >
< StickToBottom . Content className = "flex flex-col gap-4" >
{ messages . map ( ( message ) => (
< Message key = { message . id } message = { message } / >
) ) }
< / StickToBottom . Content >
< ScrollToBottom / >
{ /* This component uses `useStickToBottomContext` to scroll to bottom when the user enters a message */ }
< ChatBox / >
< / StickToBottom >
) ;
}
function ScrollToBottom ( ) {
const { isAtBottom , scrollToBottom } = useStickToBottomContext ( ) ;
return (
! isAtBottom && (
< button
className = "absolute i-ph-arrow-circle-down-fill text-4xl rounded-lg left-[50%] translate-x-[-50%] bottom-0"
onClick = { ( ) => scrollToBottom ( ) }
/ >
)
) ;
}
useStickToBottom
钩子 import { useStickToBottom } from 'use-stick-to-bottom' ;
function Component ( ) {
const { scrollRef , contentRef } = useStickToBottom ( ) ;
return (
< div style = { { overflow : 'auto' } } ref = { scrollRef } >
< div ref = { contentRef } >
{ messages . map ( ( message ) => (
< Message key = { message . id } message = { message } / >
) ) }
< / div >
< / div >
) ;
}