React模态窗口滚动实现:仅模态框滚动,阻止主窗口滚动
解决React模态框打开时主窗口禁止滚动、仅模态框可滚动的问题
要实现模态框打开时主窗口无法滚动、仅模态框内部可滚动的效果,只需完成以下两步修改:
1. 控制主窗口(body)的滚动状态
在Modal组件中通过useEffect监听模态框的打开/关闭状态,动态修改body的overflow属性,阻止主窗口滚动:
import close from '/close.png'; import add from '/add1.png'; import './Modal.css'; import MainButton2 from '../Button/MainButton2' import { useState, useRef, useEffect } from "react"; // 引入useEffect export default function Modal ({ isOpen, onClose }, props) { // 监听模态框状态,控制body滚动 useEffect(() => { if (isOpen) { document.body.style.overflow = 'hidden'; } else { document.body.style.overflow = ''; } // 组件卸载时恢复body默认状态,避免遗留副作用 return () => { document.body.style.overflow = ''; }; }, [isOpen]); if (!isOpen) return null; return ( <div className="modal-overlay"> <div className="modal-content"> <div className='thefirstrow'> <div className='newpod'>jasjssj</div> <img className='close' src={close} alt='user' style={{ cursor: 'pointer' }} onClick={onClose}/> </div> {/* 可添加更多内容测试滚动效果 */} </div> </div> ); };
2. 让模态框内容支持滚动
修改Modal.css,给modal-content添加overflow: auto属性,当内容高度超过模态框设定的630px时,自动出现内部滚动条:
.modal-overlay { position: fixed; top: 0; left: 0; right: 0; bottom: 0; background: rgba(0, 0, 0, 0.3); display: flex; justify-content: center; z-index: 2000; } .modal-content { position: absolute; background: white; border-radius: 40px; width: 64vw; height: 630px; z-index: 1001; margin-top: 100px; transform: translateY(-50%); overflow: auto; /* 新增:内容超出时显示滚动条 */ } /* 可选:自定义滚动条样式(优化视觉效果) */ .modal-content::-webkit-scrollbar { width: 6px; } .modal-content::-webkit-scrollbar-track { background: transparent; } .modal-content::-webkit-scrollbar-thumb { background-color: #ccc; border-radius: 3px; }
内容的提问来源于stack exchange,提问作者Полина Фомичева
相关产品推荐
相关产品推荐

