ReactJS如何滚动到一个元素

我有一个聊天小部件,每次向上滚动时都会拉出一个消息数组。我现在面临的问题是,当消息加载时,滑块固定在顶部,我希望它能集中在前一个数组的最后一个索引元素上。我发现我可以通过传递索引来做动态参考,但我也需要知道用什么样的滚动函数来实现这个目标。

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

  render() {

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

只要找到你已经确定的元素的顶部位置https://www.w3schools.com/Jsref/prop_element_offsettop.asp,然后通过scrollTo方法滚动到这个位置https://www.w3schools.com/Jsref/met_win_scrollto.asp

类似这样的方法应该是可行的。

handleScrollToElement(event) {
  const tesNode = ReactDOM.findDOMNode(this.refs.test)
  if (some_logic){
    window.scrollTo(0, tesNode.offsetTop);
  }
}

render() {

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

更新:

自从React v16.3以来,React.createRef()是首选。

constructor(props) {
  super(props);
  this.myRef = React.createRef();
}

handleScrollToElement(event) {
  if (){
    window.scrollTo(0, this.myRef.current.offsetTop);
  }
}

render() {

  return (
    <div>
      <div ref={this.myRef}></div>
    </div>)
}
评论(5)

使用findDOMNode最终会被废弃。

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

github eslint

评论(1)

你可以使用类似componentDidUpdate的东西

componentDidUpdate() {
  var elem = testNode //your ref to the element say testNode in your case; 
  elem.scrollTop = elem.scrollHeight;
};
评论(3)