简体   繁体   English

如何将组件滚动到底部

[英]How to scroll component to the bottom in react

I'm trying to solve kind of simple problem: when component is loaded, i need to scroll it to the bottom. 我正在尝试解决一种简单的问题:加载组件时,需要将其滚动到底部。 But i've wasted ton of hours trying to solve it. 但是我已经浪费了很多时间试图解决它。 I've tried a lot of different ways (scrollIntoView, scrollTop, scrollBy, etc...) but none of them can't do it. 我尝试了很多不同的方式(scrollIntoView,scrollTop,scrollBy等),但是没有一种方法不能做到。 Url below is a link to fiddle where i have a simple component and i need Message to be shown. 下面的网址是小提琴的链接,其中我有一个简单的组件,我需要显示Message。 The problem is that i have to scroll about 10 pixels by myself. 问题是我必须自己滚动约10个像素。 I would really appreciate if you help me to solve this problem. 如果您能帮助我解决这个问题,我将不胜感激。

class Hello extends React.Component {
  componentDidMount() {
    const elem = ReactDOM.findDOMNode(this.refs.test);

    if (elem) {
      elem.scrollIntoView(false);
    }
  }

  render() {
    return (
      <div>
        <div className="test" 
             ref="test">
             Hello {this.props.name}
        </div>
        <div>Message</div>
      </div>
    )
  }
}

ReactDOM.render(
  <Hello name="World" />,
  document.getElementById('container')
);

JSFiddle JSFiddle

You placed the ref attribute on the wrong place. 您将ref属性放在错误的位置。

Move it one level up in order to catch the whole component, including the "Message" text. 将其上移一级以捕获整个组件,包括“消息”文本。

So, basically: 因此,基本上:

class Hello extends React.Component {
  // ...

  render() {
    return (
      <div ref="test">
        <div className="test">
             Hello {this.props.name}
        </div>
        <div>Message</div>
      </div>
    )
  }
}

Here's a working jsfiddle demo , forked from yours. 这是一个工作正常的jsfiddle演示 ,从您的演示中派生而来。

  class Hello extends React.Component {
  // ...

  componentDidUpdate() {
    this.scrollDiv.scrollIntoView(false);
  }

  render() {
    return (
      <div
        ref={(el) => {this.scrollDiv = el}}
      >
        <div className="test">
             Hello {this.props.name}
        </div>
        <div>Message</div>
      </div>
    )
  }
}    

You should scroll only when the component is loaded into DOM filled with all props. 仅当将组件加载到包含所有道具的DOM中时,才应滚动。

export default class Hello extends React.Component {
  constructor(props,context){
    super(props,context);
    this.isAlreadyLoaded =  false;
   }

componentWillReceiveProps(nextProps) {
    let scrollToElement = document.getElementById("scroll-element");
    if (scrollToElement && !isAlreadyLoaded){
        this.isAlreadyLoaded = true;
        scrollToElement.scrollIntoView(true);
    }
  }

   render(){
      return {....}
   }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM