在 react.js 中渲染后滚动到页面顶部

新手上路,请多包涵

我有一个问题,我不知道如何解决。在我的反应组件中,我在底部显示了一长串数据和几个链接。单击任何此链接后,我会使用新的链接集合填写列表,并且需要滚动到顶部。

问题是 - 呈现新集合 如何滚动到顶部?

 'use strict';

// url of this component is #/:checklistId/:sectionId

var React = require('react'),
  Router = require('react-router'),
  sectionStore = require('./../stores/checklist-section-store');

function updateStateFromProps() {
  var self = this;
  sectionStore.getChecklistSectionContent({
    checklistId: this.getParams().checklistId,
    sectionId: this.getParams().sectionId
  }).then(function (section) {
    self.setState({
      section,
      componentReady: true
    });
  });

    this.setState({componentReady: false});
 }

var Checklist = React.createClass({
  mixins: [Router.State],

  componentWillMount: function () {
    updateStateFromProps.call(this);
  },

  componentWillReceiveProps(){
    updateStateFromProps.call(this);
   },

render: function () {
  if (this.state.componentReady) {
    return(
      <section className='checklist-section'>
        <header className='section-header'>{ this.state.section.name }   </header>
        <Steps steps={ this.state.section.steps }/>
        <a href=`#/${this.getParams().checklistId}/${this.state.section.nextSection.Id}`>
          Next Section
        </a>
      </section>
    );
    } else {...}
  }
});

module.exports = Checklist;

原文由 Andrew Kovalenko 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 809
2 个回答

由于最初的解决方案是为早期版本的 react 提供的,因此这里有一个更新:

 constructor(props) {
    super(props)
    this.myRef = React.createRef()   // Create a ref object
}

componentDidMount() {
  this.myRef.current.scrollTo(0, 0);
}

render() {
    return <div ref={this.myRef}></div>
}   // attach the ref property to a dom element

原文由 Andrew Kovalenko 发布,翻译遵循 CC BY-SA 4.0 许可协议

最后..我用过:

 componentDidMount() {
  window.scrollTo(0, 0)
}

编辑:React v16.8+

 useEffect(() => {
  window.scrollTo(0, 0)
}, [])

原文由 sledgeweight 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进