我有个问题,我不知道怎么解决。 在我的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 v18+,我的建议是使用包装器组件,这将是最简单的执行方式。

步骤1:创建一个ScrollToTop组件(component/ScrollToTop.js)

import { useEffect } from "react";
import { useLocation } from "react-router-dom";

export function ScrollToTop() {
  const { pathname } = useLocation();

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

  return null;
}

步骤2:用index.js包装你的应用程序

<React.StrictMode>
  <BrowserRouter>
    <ScrollToTop />
    <App />
  </BrowserRouter>
</React.StrictMode>

解释:每次路径名更改时,useEffect将被调用以将页面滚动到顶部。

其他回答

由于最初的解决方案是为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

你可以用这样的东西。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) } }

我什么都试过了,但这是唯一有效的办法。

 useLayoutEffect(() => {
  document.getElementById("someID").scrollTo(0, 0);
 });

我已经尝试过@sledgeweight解决方案,但它并不适用于某些视图。但是添加setTimeout似乎可以完美地工作。以防有人遇到和我一样的问题。下面是我的代码。

import { useEffect } from 'react'
import { useLocation } from 'react-router-dom'

const ScrollToTop = () => {
    const { pathname } = useLocation()
    useEffect(() => {
        console.log(pathname)
        /* settimeout make sure this run after components have rendered. This will help fixing bug for some views where scroll to top not working perfectly */
        setTimeout(() => {
            window.scrollTo({ top: 0, behavior: 'smooth' })
        }, 0)
    }, [pathname])
    return null
}

export default ScrollToTop

在AppRouter.js中使用它

<Router>
    <ScrollToTop/>
    <App>
</Router>

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

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

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

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

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