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

当前回答

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

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

其他回答

我在一个组件上使用了类似的方法:

<div ref="scroller" style={{height: 500, overflowX: "hidden", overflowY: "auto"}}>
      //Content Here
</div>

然后在处理更新的函数中:

this.refs.scroller.scrollTop=0

这就是我所做的:

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

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

看起来所有的useEffect例子都没有考虑到你可能想要通过状态改变来触发这个。

const [aStateVariable, setAStateVariable] = useState(false);

const handleClick = () => {
   setAStateVariable(true);
}

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

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

点击后出现的页面,只需在其中写入即可。

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