use stick to bottom
1.0.0
useStickToBottom
ออกแบบโดยคำนึงถึงบอทแชท AI เป็นหลัก ขับเคลื่อน
bolt.new
โดย StackBlitz
React hook + Component น้ำหนักเบา ที่ไม่ต้องพึ่งพิงใด ๆ ซึ่งจะเกาะที่ด้านล่างของคอนเทนเนอร์โดยอัตโนมัติ และเคลื่อนไหวเนื้อหาได้อย่างราบรื่นเพื่อรักษาตำแหน่งที่มองเห็นได้บนหน้าจอในขณะที่มีการเพิ่มเนื้อหาใหม่
overflow-anchor
ซึ่ง Safari ไม่รองรับ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
ตะขอ StickToBottom 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 >
) ;
}