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>
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745476042a4629351.html
评论列表(0条)