我有个问题,我不知道怎么解决。 在我的react组件中,我在底部显示了一个很长的数据列表和一些链接。 点击任何链接后,我在列表中填充了新的链接集合,需要滚动到顶部。

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

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

当前回答

你可以在路由器上这样做:

ReactDOM.render((
<Router onUpdate={() => window.scrollTo(0, 0)} history={browserHistory}>
     <Route path='/' component={App}>
        <IndexRoute component={Home}></IndexRoute>
        <Route path="/about" component={About}/>
        <Route path="/work">
            <IndexRoute component={Work}></IndexRoute>
            <Route path=":id" component={ProjectFull}></Route>
        </Route>
        <Route path="/blog" component={Blog}/>
    </Route>
 </Router>
), document.getElementById('root'));

onUpdate={() =>窗口。scrollTo(0,0)}将滚动顶部。 更多信息请查看:codepen link

其他回答

平滑滚动到顶部。在钩子中,你可以在生命周期安装状态中使用此方法进行一次渲染

useEffect(() => {
  window.scrollTo({top: 0, left: 0, behavior: 'smooth' });
}, [])

你可以用这样的东西。ReactDom是react的缩写。否则只需React即可。

    componentDidUpdate = () => { ReactDom.findDOMNode(this).scrollIntoView(); }

2019年5月11日更新React 16+

构造函数(道具){ 超级(道具) 这一点。childDiv = React.createRef() } componentDidMount = () => this.handleScroll() componentDidUpdate = () => this.handleScroll() handleScroll = () => { Const {index, selected} = this.props If (index === selected) { setTimeout(() => { this.childDiv.current。scrollIntoView({behavior: 'smooth'}) }, 500) } }

在功能组件中使用hook, 假设在结果道具中有更新时组件更新

import React, { useEffect } from 'react';

export const scrollTop = ({result}) => {
  useEffect(() => {
    window.scrollTo(0, 0);
  }, [result])
}

对于那些使用钩子的人,下面的代码可以工作。

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

注意,你也可以直接导入useEffect:

没有什么对我有用,除了:

componentDidMount(){

    $( document ).ready(function() {
        window.scrollTo(0,0);
    });
}