解決方法がわからない問題があります。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;
ベストアンサー1
最後に、私が使用したのは:
componentDidMount() {
window.scrollTo(0, 0)
}
編集: React v16.8+
useEffect(() => {
window.scrollTo(0, 0)
}, [])