【问题标题】:Scroll to the top of the page after render in react.js在 react.js 中渲染后滚动到页面顶部
【发布时间】:2016-01-16 07:11:17
【问题描述】:

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

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

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

【问题讨论】:

标签: scroll reactjs render


【解决方案1】:

我有一段时间有同样的问题。添加 window.scrollTo(0, 0); 到每一页都是痛苦和多余的。所以我添加了一个 HOC,它将包装我的所有路由,并将保留在 BrowserRouter 组件中:

 <ScrollTop>
    <Routes />
  </ScrollTop>

在 ScrollTopComponent 我们有以下内容:

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

const ScrollTop = (props) => {
  const { children } = props;

  const location = useLocation();

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

  return <main>{children}</main>;
};

export default ScrollTop;

【讨论】:

    【解决方案2】:

    看起来所有 useEffect 示例都没有考虑到您可能希望通过状态更改来触发它。

    const [aStateVariable, setAStateVariable] = useState(false);
    
    const handleClick = () => {
       setAStateVariable(true);
    }
    
    useEffect(() => {
      if(aStateVariable === true) {
        window.scrollTo(0, 0)
      }
    }, [aStateVariable])
    

    【讨论】:

      【解决方案3】:

      我在 React 17.0 中使用功能组件和 window.scroll、window.scrollTo 做一个 SPA,所有这些变体都对我不起作用。所以我使用 useRef 钩子做了一个解决方案。我使用 Ref 在组件顶部创建了一个 span 标签,然后使用 ref.current.scrollIntoView() 并使用效果

      有一个简短的例子:

      import React, { useEffect,useRef} from 'react';
      
      export const ExampleComponent = () => {
      
        const ref = useRef();
      
        useEffect(() => {
            ref.current.scrollIntoView()
        }, []);
      
      return(
      
       <>
         <span ref={ref}></span>
         <YourCodeHere />
         <MoreCode />
      </>
      

      ) }

      【讨论】:

        【解决方案4】:

        功能组件的解决方案 - 使用 useEffect() 钩子

         useEffect(() => {
        window.history.scrollRestoration = 'manual';}, []);
        

        【讨论】:

          【解决方案5】:

          此解决方案适用于功能组件以及类库。

          首先,我不喜欢每次重新渲染时滚动到顶部的想法,相反,我喜欢特定事件的附加功能。

          第 1 步:创建一个 ScrollToTop 函数

          const scrollToTop = () => {
              window.scrollTo({
                  top: 0,
                  behavior: "smooth",
              });
          };
          

          第 2 步:在 event 上调用此函数,例如 onClick

          onRowClick={scrollToTop()}
          // onClick={scrollToTop()}
          // etc...
          

          【讨论】:

            【解决方案6】:

            我尝试过@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>
            

            【讨论】:

              猜你喜欢
              • 2015-08-02
              • 2013-09-26
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多