我有一个自定义模态组件。当它打开时,背景中没有任何滚动。
我在下面尝试了这段代码:
componentDidMount() {
document.body.style.overflow = 'hidden';
}
componentWillUnmount() {
document.body.style.overflow = 'unset';
}
这似乎一开始有效,但是当我使用模态组件时,在另一个页面中,即使模态关闭也没有滚动。
有更好的解决方案吗?
我的模态组件:
export class Modal extends React.Component {
constructor(props) {
super(props);
}
componentDidMount() {
document.body.style.overflow = 'hidden';
}
componentWillUnmount() {
document.body.style.overflow = 'unset';
}
render() {
return (
<React.Fragment>
{this.props.showAt ?
this.props.show ?
<div style={style} className={`${this.props.sectionName} ${modalTypeStyle ? modalTypeStyle : styles.modalWhite} ${modalTypeSize ? modalTypeSize : styles.modalSmall} ${!this.props.showAt ? styles.modalWhiteFixed : ""}`}>
{this.props.arrowShape ? <div className={arrowTypeStyle ? arrowTypeStyle : styles.triangleToprightWhite} /> : null}
{this.props.children}
</div>
: null
:
this.props.show ?
<div className={`${this.props.className} ${styles.modal}`}>
<div style={style} className={`${this.props.sectionName} ${modalTypeStyle ? modalTypeStyle : styles.modalWhite} ${modalTypeSize ? modalTypeSize : styles.modalSmall} ${!this.props.showAt ? styles.modalWhiteFixed : ""}`}>
{this.props.arrowShape ? <div className={arrowTypeStyle ? arrowTypeStyle : styles.triangleToprightWhite} /> : null}
{this.props.children}
</div>
</div> :
null}
</React.Fragment>
)
}
}
原文由 RCohen 发布,翻译遵循 CC BY-SA 4.0 许可协议
使用 state 来跟踪模态框是否打开,只有在打开时才隐藏滚动条。由于您在
document.body.style.overflow = 'hidden'
componentDidMount
,因此组件仍会被挂载,它会调用生命周期方法来隐藏身体上的滚动条。