我有个问题,我不知道怎么解决。 在我的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 Hooks,想要一些可重用的东西,但也想要一些我可以随时调用的东西(而不是仅仅在渲染之后)。

// utils.js
export const useScrollToTop = (initialScrollState = false) => {
  const [scrollToTop, setScrollToTop] = useState(initialScrollState);

  useEffect(() => {
    if (scrollToTop) {
      setScrollToTop(false);
      try {
        window.scroll({
          top: 0,
          left: 0,
          behavior: 'smooth',
        });
      } catch (error) {
        window.scrollTo(0, 0);
      }
    }
  }, [scrollToTop, setScrollToTop]);

  return setScrollToTop;
};

然后使用钩子你可以做:

import { useScrollToTop } from 'utils';

const MyPage = (props) => {
  // initialise useScrollToTop with true in order to scroll on page load 
  const setScrollToTop = useScrollToTop(true);

  ...

  return <div onClick={() => setScrollToTop(true)}>click me to scroll to top</div>
}

其他回答

如果所有人都想做一些简单的事情,这里有一个解决方案,对每个人都适用

添加这个迷你函数

scrollTop()
{
    window.scrollTo({
        top: 0,
        behavior: "smooth"
    });
}

从页脚调用函数,如下所示

<a className="scroll-to-top rounded" style={{display: "inline"}} onClick={this.scrollTop}>TOP</a>

如果你想添加漂亮的样式,这里是CSS

.scroll-to-top { 位置:固定; 右:1快速眼动; 底部:1快速眼动; 显示:没有; 宽度:2.75快速眼动; 高度:2.75快速眼动; text-align:中心; 颜色:# fff; 背景:rgba(90,92,105,0.5); 行高:46 px; }

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

我在React 17.0中使用功能组件和窗口做SPA。滚动窗口。scrollTo和所有这些变体都不适合我。所以我用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 />
</>

) }

useEffect(() => {
    const body = document.querySelector('#root');

    body.scrollIntoView({
        behavior: 'smooth'
    }, 500)

}, []);

这是查看顶部滚动页面的最佳解决方案

或者使用ref来跳转页面

    // a link jump to page react
const ref = useRef(null);

  const handleClick = () => {
    ref.current?.scrollIntoView({behavior: 'smooth'});
  };

 <button onClick={handleClick}>Scroll to element</button>
 <div ref={ref}>Some content here</div>

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