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

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

  render() {

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

当前回答

对我有用的是:

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

其他回答

我有一个简单的场景,当用户点击我的材质UI导航栏的菜单项时,我想要向下滚动到页面上的部分。我可以使用引用和线程他们通过所有的组件,但我讨厌线程道具通过多个组件,因为这使得代码脆弱。

我只是在我的react组件中使用了香草JS,结果证明它工作得很好。在我想要滚动的元素上放置一个ID,在我的头组件中,我只是这样做了。

const scroll = () => {
  const section = document.querySelector( '#contact-us' );
  section.scrollIntoView( { behavior: 'smooth', block: 'start' } );
};

2019年7月-专用钩子/函数

专用的钩子/函数可以隐藏实现细节,并为组件提供简单的API。

React 16.8 +功能组件

const useScroll = () => {
  const elRef = useRef(null);
  const executeScroll = () => elRef.current.scrollIntoView();

  return [executeScroll, elRef];
};

在任何功能组件中使用它。

const ScrollDemo = () => {
    const [executeScroll, elRef] = useScroll()
    useEffect(executeScroll, []) // Runs after component mounts
    
    return <div ref={elRef}>Element to scroll to</div> 
}

完整的演示

React 16.3 +类组件

const utilizeScroll = () => {
  const elRef = React.createRef();
  const executeScroll = () => elRef.current.scrollIntoView();

  return { executeScroll, elRef };
};

在任何类组件中使用它。

class ScrollDemo extends Component {
  constructor(props) {
    super(props);
    this.elScroll = utilizeScroll();
  }

  componentDidMount() {
    this.elScroll.executeScroll();
  }

  render(){
    return <div ref={this.elScroll.elRef}>Element to scroll to</div> 
  }
} 

完整的演示

还可以使用scrollIntoView方法滚动到给定元素。

handleScrollToElement(event) {
const tesNode = ReactDOM.findDOMNode(this.refs.test)
 if (some_logic){
  tesNode.scrollIntoView();
  }
 }

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

你可以使用useRef和scrollIntoView。

使用useReffor你想滚动到的元素:这里我想滚动到PieceTabs元素,这就是为什么我用一个盒子(div)包装它,这样我就可以访问dom元素

您可能对refs很熟悉,它主要是作为一种访问DOM的方式。如果你传递一个ref对象给React, React会在相应的DOM节点发生变化时将其.current属性设置为相应的DOM节点。看医生

...
const tabsRef = useRef()
...
<Box ref={tabsRef}>
   <PieceTabs piece={piece} value={value} handleChange={handleChange} />
</Box>
...

创建一个处理滚动的函数:

  const handleSeeCompleteList = () => {
    const tabs = tabsRef.current
    if (tabs) {
      tabs.scrollIntoView({
        behavior: 'smooth',
        block: 'start',
      })
    }
  }

当你点击滚动到目标时,在你想要的元素上调用这个函数:

 <Typography
  variant="body2"
  sx={{
    color: "#007BFF",
    cursor: "pointer",
    fontWeight: 500,
  }}
  onClick={(e) => {
    handleChange(e, 2);
    handleSeeCompleteList(); // here we go
  }}
>
  Voir toute la liste
</Typography>;

好了

<div id="componentToScrollTo"><div>

<a href='#componentToScrollTo'>click me to scroll to this</a>