我有个问题,我不知道怎么解决。 在我的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;

当前回答

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

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

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

其他回答

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

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

最后. .我使用:

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

编辑:React v16.8+

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

这就是我所做的:

useEffect(() => ref.current.scrollTo(0, 0));
const ref = useRef()

       return(
         <div ref={ref}>
           ...
         </div>
        )

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

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

我遇到了这个问题,与盖茨比建立一个网站,其链接是建立在Reach路由器的顶部。这似乎很奇怪,这是一个必须做出的修改,而不是默认的行为。

不管怎样,我尝试了上面的许多解决方案,唯一对我有效的是:

document.getElementById("WhateverIdYouWantToScrollTo").scrollIntoView()

我把它放在一个useEffect中,但你也可以很容易地把它放在componentDidMount中,或者以任何你想要的方式触发它。

不知道为什么是窗口。scrollTo(0,0)对我(和其他人)不起作用。