使用react-modal时如何实现小屏超长模态框的垂直滚动功能
解决方案
问题根源:你当前配置的react-modal content容器未做最大高度限制,固定600px高的内容容器在小屏视口高度不足时,整个模态框会直接溢出视口,没有触发滚动的规则,导致内容无法查看。
核心修改点
- 给modal的content样式添加
maxHeight限制为90vh(占视口高度的90%,预留安全边距) - 给content或内部内容容器添加
overflowY: auto,超出高度时自动显示滚动条
修改后完整代码
import React, { useState } from "react"; import styled from "styled-components"; import Modal from "react-modal"; export default function App() { const [isOpen, setModal] = useState(true); const Container = styled.div<{ height?: string }>` width: 400px; // 把固定height改成maxHeight适配不同屏幕 max-height: ${({ height }) => (height ? height : "")}; overflow-y: auto; display: flex; flex-direction: column; background: #ffffff; `; const customStyles = { overlay: { background: "rgba(0, 0, 0, 0.5)" }, content: { top: "50%", left: "50%", right: "auto", bottom: "auto", marginRight: "-50%", transform: "translate(-50%, -50%)", padding: "0", // 新增两条样式限制模态框最大高度 maxHeight: "90vh", overflowY: "auto" } }; return ( <> <Modal isOpen={isOpen} onRequestClose={() => { setModal(false); }} contentLabel="modal" style={customStyles} > <p>Modal</p> <Container height={"600px"}></Container> </Modal> </> ); }
可选优化(头部固定仅内容滚动)
如果需要Modal标题固定不随内容滚动,可以调整结构和样式:
- 移除content上的
overflowY: auto配置 - 给标题添加sticky定位,调整内容容器的最大高度为
calc(90vh - 标题高度):
<Modal isOpen={isOpen} onRequestClose={() => setModal(false)} contentLabel="modal" style={customStyles} > <p style={{ position: 'sticky', top: 0, background: '#fff', margin: 0, padding: '16px' }}>Modal</p> {/* 减去标题的高度+padding总和,这里按56px计算 */} <Container height={"calc(90vh - 56px)"}></Container> </Modal>
内容的提问来源于stack exchange,提问作者user15375616
相关产品推荐
相关产品推荐

