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

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

  render() {

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

当前回答

使用findDOMNode最终将被弃用。

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

Github Eslint

其他回答

如果有人在使用Typescript,下面是Ben Carp的答案:

import { RefObject, useRef } from 'react';

export const useScroll = <T extends HTMLElement>(
  options?: boolean | ScrollIntoViewOptions
): [() => void, RefObject<T>] => {
  const elRef = useRef<T>(null);
  const executeScroll = (): void => {
    if (elRef.current) {
      elRef.current.scrollIntoView(options);
    }
  };

  return [executeScroll, elRef];
};

最好的方法是使用element。scrollIntoView({behavior: 'smooth'})。这将以漂亮的动画将元素滚动到视图中。

当你将它与React的useRef()结合使用时,可以通过以下方式完成。

import React, { useRef } from 'react'

const Article = () => {
  const titleRef = useRef()

  function handleBackClick() {
      titleRef.current.scrollIntoView({ behavior: 'smooth' })
  }

  return (
      <article>
            <h1 ref={titleRef}>
                A React article for Latin readers
            </h1>

            // Rest of the article's content...

            <button onClick={handleBackClick}>
                Back to the top
            </button>
        </article>
    )
}

当你想要滚动到React组件时,你需要将引用转发给渲染的元素。本文将深入探讨这个问题。

使用findDOMNode最终将被弃用。

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

Github Eslint

对于读到这篇文章的人来说,如果他们没有那么幸运地使用上述解决方案,或者只是想要一个简单的即时解决方案,那么这个软件包对我来说很有用:https://www.npmjs.com/package/react-anchor-link-smooth-scroll。黑客快乐!

对我有用的是:

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>
        )
    }
}