最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Render a div in React with an initial scrollTop value set - Stack Overflow

programmeradmin1浏览0评论

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>

发布评论

评论列表(0)

  1. 暂无评论