我有一个自定义模态组件。当它打开时,后台没有任何滚动。
我试过下面这段代码:
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>
)
}
}
最佳答案
使用状态来跟踪模态框是否打开,只有在打开时才隐藏滚动条。由于您在 componentDidMount
中使用了 document.body.style.overflow = 'hidden'
,组件仍然会被挂载,这会调用生命周期方法来隐藏 body 上的滚动条。
export class Modal extends React.Component {
constructor(props) {
super(props);
this.state = {
open:false
}
}
componentDidMount() {
if(this.state.open){
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>
)
}
}
关于javascript - react : Prevent scroll when modal is open,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54989513/