在 react.js 中渲染后滚动到页面顶部 [英] Scroll to the top of the page after render in react.js

查看:37
本文介绍了在 react.js 中渲染后滚动到页面顶部的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个问题,我不知道如何解决.在我的 React 组件中,我在底部显示了一长串数据和几个链接.点击任何一个链接后,我用新的链接集合填充列表,并需要滚动到顶部.

I have a problem, which I have no ideas, how to solve. In my react component I display a long list of data and few links at the bottom. After clicking on any of this links I fill in the list with new collection of the links and need to scroll to the top.

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

The problem is - how to scroll to the top after new collection is rendered?

'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;

推荐答案

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

Since the original solution was provided for very early version of react, here is an update:

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

这篇关于在 react.js 中渲染后滚动到页面顶部的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆