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

I have a React ponent which is rendering a div. However I want this div to be rendered such that it

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>

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745476042a4629351.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信