[英]How to Make a Fixed Element Stay Relative to the Current Top Scroll Position?
[英]Reactjs, How to make scroll stay at current position when scrollable div extends
我正在嘗試構建一個 React Chat 應用程序,我打算使用無限滾動,但它沒有按照我想要的方式工作。 所以我自己建了一個。 我使用 useref 來確定高度,如果它到達頂部,它將添加更多聊天。 有點像 fb 信使的聊天。 現在的問題是,當我添加更多聊天時,一旦它到達頂部,滾動條將繼續向上移動,而不是像 react-infinite scroll 那樣工作。
我可以知道我該如何度過這一切嗎? 這是我的代碼。 對於卷軸:
const onScroll = () => {
if (topDiv.current) {
const { scrollTop, scrollHeight, clientHeight } = topDiv.current;
if(scrollTop === 0){
props.fecthMoreChat()
}
}
};
return(
<div id='scrollableDiv' ref={topDiv} onScroll={()=> onScroll()} style={{height:'100%', padding:'20px', display:'flex', flexDirection:'column', backgroundColor:'#efefef', overflowY:'scroll'}}>
{/* <div style={{visibility:'hidden'}} ref={topDiv}></div> */}
{currentChat.map((chat, index)=>{
return(
<div key={index} style={{textAlign:chat.sender===username?'right':'left'}}>
{chat.message}
</div>
)
})}
<div style={{visibility:'hidden'}} ref={botMsg}></div>
</div>
)
所以答案其實很簡單。 我只是獲取當前滾動高度,將其保存在一個變量中,然后等待重新渲染並獲取新的滾動高度。 基本上,只需用新的滾動高度減去舊的滾動高度,並使用該數字通過使用scrollTo()
設置滾動。 這是代碼:
const onScroll = async () => {
if (chatDiv.current) {
const { scrollTop, scrollHeight, clientHeight } = chatDiv.current;
if(scrollTop === 0){
const pastScroll = scrollHeight
await props.fecthMoreChat()
const currentScroll = (await chatDiv.current.scrollHeight-pastScroll)
await chatDiv.current.scrollTo(0, currentScroll)
}
}
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.