admin管理员组文章数量:1426959
I have a React ponent which is rendering a div
. However I want this div
to be rendered such that it's initially scrolled all the way to the bottom.
I know this can be achieved by using a ref
and setting the scrollTop
property in ponentDidMount
(or in useEffect
), but this causes a flicker when the div
is initially rendered.
If the div
is rendered with the scrollTop
property already set on the DOM Element, then the flicker will not occur.
React does not support a scrollTop
property for the div
. So is there any way to set an initial scrollTop
value before the ponent is mounted?
I have a React ponent which is rendering a div
. However I want this div
to be rendered such that it's initially scrolled all the way to the bottom.
I know this can be achieved by using a ref
and setting the scrollTop
property in ponentDidMount
(or in useEffect
), but this causes a flicker when the div
is initially rendered.
If the div
is rendered with the scrollTop
property already set on the DOM Element, then the flicker will not occur.
React does not support a scrollTop
property for the div
. So is there any way to set an initial scrollTop
value before the ponent is mounted?
-
1
Why would there be a flicker?
ponentDidMount
is executed before browser updates the screen. Is it an async operation? – Agney Commented Feb 24, 2019 at 15:10 -
1
Actually, I'm using the
useEffect
hook, notponentDidMount
, so that's why I'm getting a flicker. – asleepysamurai Commented Feb 24, 2019 at 15:12
1 Answer
Reset to default 6You can use the useLayoutEffect
hook to run some logic synchronously after all DOM mutations. These updates will be flushed synchronously, before the browser has a chance to paint.
const { useRef, useLayoutEffect } = React;
function App() {
const ref = useRef(null);
useLayoutEffect(() => {
ref.current.scrollTop = ref.current.scrollHeight;
}, []);
return (
<div
ref={ref}
style={{
height: 100,
overflowY: "scroll"
}}
>
<div style={{ height: 1000 }} />
<div>Foo</div>
</div>
);
}
ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://unpkg./react@16/umd/react.development.js"></script>
<script src="https://unpkg./react-dom@16/umd/react-dom.development.js"></script>
<div id="root"></div>
本文标签: javascriptRender a div in React with an initial scrollTop value setStack Overflow
版权声明:本文标题:javascript - Render a div in React with an initial scrollTop value set - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745476041a2659967.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论