我使用react-bootstrap-sweetalert
lib制作了一个模态窗口。它包含很长的内容列表,所以我允许overflow:scroll
。问题是什么,当模态打开时,它不会滚动到顶部。并滚动到未知位置,所以我需要手动滚动到顶部。
这是简单的代码
basicAlert = () => {
this.setState({
alert: (
<div>
// long list table
</div>)
});
}
hideAlert = () => {
this.setState({
alert: null
});
}
render() {
return (
{this.state.alert}
// rest contents ...
)
}
任何建议对我都有很大的帮助。谢谢
你可以创建一个ref
到你的组件中包含可滚动内容的元素,然后使用这个引用将scrollTop
设置为相应DOM元素的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>)
}