简体   繁体   English

React Hook 在页面加载时滚动到溢出 div 的底部

[英]React Hook Scroll to bottom of overflowing div on page load

I would like to scroll only an overflowing div while keeping the rest of the page at the normal starting position.我只想滚动一个溢出的 div,同时将页面的其余部分保持在正常的起始位置。 Right now I'm getting a Cannot read property 'scrollIntoView' of null error when calling UseEffect现在,我在调用UseEffect时遇到了Cannot read property 'scrollIntoView' of null错误的Cannot read property 'scrollIntoView' of null

Code代码

import React, {Fragment, useEffect, useRef} from 'react';

const VideoPlayer = ({...foo...}) => {

   const chatRef = useRef(null)
       const scroll = () => {
           chatRef.current.scrollIntoView();
       }


   useEffect(() => {
           foo_function
           scroll()
       }, [foo_function]);

   }

   return (
   ...other-non-overflowing-div-content...

   <div>
      <div ref={chatRef}>
         <Link to={'/login'}>
           <p className='chat-sign-in'>Sign in to usechat</p>
         </Link>
       </div>
   </div>

   )
 }


在此处输入图片说明

You don't need the useRef .您不需要useRef Try a callback ref instead.尝试使用回调引用 You can also pass it as a function with same signature.您也可以将其作为具有相同签名的函数传递。

<div ref={el => el.scrollintoview()}/>

Or或者

const cb = el => {
  foo();
  el.scrollintoview();
}

<div ref={cb}/>

Use useLayoutEffect instead useEffect使用useLayoutEffect代替useEffect

Here is a sandbox for a simple use-case这是一个简单用例的沙箱

https://codesandbox.io/s/crazy-pasteur-44rfz?file=/src/App.js https://codesandbox.io/s/crazy-pasteur-44rfz?file=/src/App.js

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM