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?

Share Improve this question asked Feb 24, 2019 at 14:55 asleepysamuraiasleepysamurai 1,3622 gold badges14 silver badges23 bronze badges 2
  • 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, not ponentDidMount, so that's why I'm getting a flicker. – asleepysamurai Commented Feb 24, 2019 at 15:12
Add a ment  | 

1 Answer 1

Reset to default 6

You 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