我有一个聊天小部件,每当我向上滚动时,它就会弹出一个消息数组。我现在面临的问题是,当消息加载时,滑块固定在顶部。我想让它关注上一个数组的最后一个索引元素。我发现我可以通过传递索引来进行动态引用,但我也需要知道使用哪种滚动函数来实现这一点

 handleScrollToElement(event) {
    const tesNode = ReactDOM.findDOMNode(this.refs.test)
    if (some_logic){
      //scroll to testNode      
    }
  }

  render() {

    return (
      <div>
        <div ref="test"></div>
      </div>)
  }

当前回答

如果你想在页面加载时做,你可以使用useLayoutEffect和useRef。

import React, { useRef, useLayoutEffect } from 'react'

const ScrollDemo = () => {

   const myRef = useRef(null)

   useLayoutEffect(() => {
      window.scrollTo({
        behavior: "smooth",
        top: myRef.current.offsetTop,
      });
    }, [myRef.current]);

   return (
      <> 
         <div ref={myRef}>I wanna be seen</div>
      </>
   )
}

其他回答

也许有人会遇到像我这样的情况

https://reactjs.org/docs/hooks-faq.html#how-can-i-measure-a-dom-node

如何度量DOM节点? 测量DOM节点位置或大小的一种基本方法是使用回调ref。每当ref附加到不同的节点时,React就会调用该回调。下面是一个小演示:

function MeasureExample() {
  const [height, setHeight] = useState(0);

  const measuredRef = useCallback(node => {
    if (node !== null) {
      setHeight(node.getBoundingClientRect().height);// you can scroll in this line 
    }
  }, []);

  return (
    <>
      <h1 ref={measuredRef}>Hello, world</h1>
      <h2>The above header is {Math.round(height)}px tall</h2>
    </>
  );
}

在本例中,我们没有选择useRef,因为对象引用不会通知我们当前引用值的更改。使用回调引用可以确保即使稍后子组件显示了被测量的节点(例如,在响应单击时),我们仍然会在父组件中得到关于它的通知,并可以更新测量值。

注意,我们将[]作为依赖数组传递给useCallback。这确保了我们的ref回调在重新渲染之间不会改变,所以React不会不必要地调用它。

在这个例子中,回调ref只会在组件挂载和卸载时被调用,因为呈现的组件在任何重新呈现器中都保持存在。如果你想在组件调整大小时收到通知,你可以使用ResizeObserver或在其上构建的第三方Hook。

只是提醒一下,我无法让这些解决方案在Material UI组件上工作。看起来他们没有当前的属性。

我只是在我的组件中添加了一个空div,并设置了ref prop。

我在一个onclick函数中使用它来平滑地滚动到一个div,其id为“step2Div”。

let offset = 100;
window.scrollTo({
    behavior: "smooth",
    top:
    document.getElementById("step2Div").getBoundingClientRect().top -
    document.body.getBoundingClientRect().top -
    offset
});

使用findDOMNode最终将被弃用。

首选的方法是使用回调引用。

Github Eslint

对我有用的是:

class MyComponent extends Component {
    constructor(props) {
        super(props);
        this.myRef = React.createRef(); // Create a ref    
    }

    // Scroll to ref function
    scrollToMyRef = () => {
        window.scrollTo({
            top:this.myRef.offsetTop, 
            // behavior: "smooth" // optional
        });
    };

    // On component mount, scroll to ref
    componentDidMount() {
        this.scrollToMyRef();
    }

    // Render method. Note, that `div` element got `ref`.
    render() {
        return (
            <div ref={this.myRef}>My component</div>
        )
    }
}