Javascript React:[useRef,scrollIntoView,]如何仅自动滚动溢出页面中的特定div?

Javascript React:[useRef,scrollIntoView,]如何仅自动滚动溢出页面中的特定div?,javascript,reactjs,scroll,react-hooks,js-scrollintoview,Javascript,Reactjs,Scroll,React Hooks,Js Scrollintoview,正如你在我的例子中看到的 const rootElement=document.getElementById(“根”); render(,rootElement); 函数App(){ 常量项=[“这个”、“那个”、“那个”、“他们”、“这些”、“这个”]; const messagesRef=React.useRef(null); 常量scrollToBottom=()=>{ messagesRef.current.scrollIntoView({ 行为:“平稳” }); }; React.u

正如你在我的例子中看到的

const rootElement=document.getElementById(“根”);
render(,rootElement);
函数App(){
常量项=[“这个”、“那个”、“那个”、“他们”、“这些”、“这个”];
const messagesRef=React.useRef(null);
常量scrollToBottom=()=>{
messagesRef.current.scrollIntoView({
行为:“平稳”
});
};
React.useffect(()=>{
if(messagesRef.current){
scrollToBottom();
}
},[messagesRef]);
返回(
//页面溢出,请设置高度以模拟整页
{/*现在将此div设置为具有较小高度的溢出滚动*/}
{items.map(elem=>(
{elem}
))}
{/*将此div中的最后一个元素设置为要滚动到*/}
);
}

试试这个:

   messagesRef.current.scrollIntoView({
      behavior: "smooth",
      block: "nearest",
      inline: "start"
    });

有趣的是,您的代码也会导致父帧滚动…对,这就是我试图颠覆的本质
scrollToBottom
也应该作为
useEffect
hook的依赖项添加。如何给出边距顶部(偏移)?