你可以创建一个
ref
到组件中包装可滚动内容的元素,然后使用此引用设置
scrollTop
到
0
因此,例如,对组件的以下添加/调整应能满足您的需要:
// Add a constructor to create the ref
constructor(props) {
super(props)
// Add a component ref to your component. You'll use this to set scroll
// position of div wrapping content
this.componentRef = React.createRef();
}
basicAlert = () => {
this.setState({
alert: (
<div>
// long list table
</div>)
}, () => {
// After state has been updated, set scroll position of wrapped div
// to scroll to top
this.componentRef.current.scrollTop = 0;
});
}
render() {
// Register your ref with wrapper div
return (<div ref={ this.componentRef }>
{ this.state.alert }
// rest contents ...
</div>)
}