首页 > 解决方案 > 模态打开时防止滚动

问题描述

我的反应应用程序上有一个模态,但是当模态处于活动状态时,我正在努力停用溢出。我正在使用以下逻辑:

零件:

import React, { Component } from 'react';
import classes from './Modal.css';
import BackDrop from '../Backdrop/Backdrop';

class Modal extends Component {
    componentDidUpdate() {
        if (this.props.show) {
            document.body.style.overflow = 'hidden';
        }
    }

    shouldComponentUpdate(nextProps, nextState) {
        return (
            nextProps.show !== this.props.show ||
            nextProps.children !== this.props.children
        );
    }

    render() {
        return (
            <div>
                <BackDrop show={this.props.show} clicked={this.props.clicked} />
                <div
                    className={
                        this.props.singleItemOptions ? classes.ItemOptions : classes.Modal
                    }
                    style={{
                        transform: this.props.show ? 'translateY(0)' : 'translateY(-100vh)',
                        opacity: this.props.show ? '1' : '0',
                    }}
                >
                    {this.props.children}
                </div>
            </div>
        );
    }
}

export default Modal;

我检查了 DOM 树,当模式处于活动状态时,样式属性出现在 body 元素标记中。不知道可能是什么问题。我期待这会起作用,因为其他人使用它。这可能与我的应用程序上的其他 CSS 样式有关吗?

标签: cssreactjs

解决方案


推荐阅读