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 >
) ;
}