无法在 React 模式中垂直滚动
P粉760675452
P粉760675452 2023-09-16 11:18:16
[CSS3讨论组]

我正在尝试在我的 React 项目中显示模式。当模态显示时,我通过 useEffect 将 body 的溢出设置为隐藏(否则,它会显示模态下方主页内容的滚动条)。它可以完美地防止背景内容滚动,但问题是我也无法在模式中滚动。 主页面代码如下:

import React, { useState } from "react";
import { render } from "react-dom";
import MyModal from "./MyModal";
import "./index.css";

function App() {
  const [showModal, setShowModal] = useState(false);
  return (
    <div className="wrapper">
      <button
        onClick={() => {
          setShowModal((current) => !current);
        }}
      >
        {`${showModal ? "Hide Modal" : "Show Modal"}`}
      </button>
      {showModal && <MyModal {...{ showModal, setShowModal }} />}
      <p>
        Lorem Ipsum is simply dummy text of the printing and typesetting
        industry. Lorem Ipsum has been the industry's standard dummy text ever
        since the 1500s, when an unknown printer took a galley of type and
        scrambled it to make a type specimen book. It has survived not only five
        centuries, but also the leap into electronic typesetting, remaining
        essentially unchanged. It was popularised in the 1960s with the release
        of Letraset sheets containing Lorem Ipsum passages, and more recently
        with desktop publishing software like Aldus PageMaker including versions
        of Lorem Ipsum.
      </p>
      
    </div>
  );
}

render(<App />, document.getElementById("root"));

这是模态的代码:

import { useEffect } from "react";
import "./modal.css";

const MyModal = ({ showModal, setShowModal }) => {
  useEffect(() => {
    document.body.style.overflowY = "hidden";
    return () => {
      document.body.style.overflowY = "auto";
    };
  }, []);
  return (
    <div className="modal-background">
      <button
        onClick={() => {
          setShowModal(false);
        }}
      >
        Close
      </button>
      <p className="heading">This is Modal</p>
      <p>
        Lorem Ipsum is simply dummy text of the printing and typesetting
        industry. Lorem Ipsum has been the industry's standard dummy text ever
        since the 1500s, when an unknown printer took a galley of type and
      </p>
    </div>
  );
};

export default MyModal;

这是codesandbox的实时示例:https://codesandbox.io/s/lockingmodal-8mvn36?file=/index.js:1160-4493

P粉760675452
P粉760675452

全部回复(1)
P粉317679342

将这两行添加到您的类“modal-background”

height:50vh;
overflow:auto;
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号