[英]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.