[英]React Hook Scroll to bottom of overflowing div on page load
我只想滾動一個溢出的 div,同時將頁面的其余部分保持在正常的起始位置。 現在,我在調用UseEffect
時遇到了Cannot read property 'scrollIntoView' of null
錯誤的Cannot read property 'scrollIntoView' of null
代碼
import React, {Fragment, useEffect, useRef} from 'react';
const VideoPlayer = ({...foo...}) => {
const chatRef = useRef(null)
const scroll = () => {
chatRef.current.scrollIntoView();
}
useEffect(() => {
foo_function
scroll()
}, [foo_function]);
}
return (
...other-non-overflowing-div-content...
<div>
<div ref={chatRef}>
<Link to={'/login'}>
<p className='chat-sign-in'>Sign in to usechat</p>
</Link>
</div>
</div>
)
}
您不需要useRef
。 嘗試使用回調引用。 您也可以將其作為具有相同簽名的函數傳遞。
<div ref={el => el.scrollintoview()}/>
或者
const cb = el => {
foo();
el.scrollintoview();
}
<div ref={cb}/>
使用useLayoutEffect
代替useEffect
這是一個簡單用例的沙箱
https://codesandbox.io/s/crazy-pasteur-44rfz?file=/src/App.js
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.