如何实现点击Ant Design日历单元格时弹出定位模态框?
实现Ant Design日历单元格点击弹出定位模态框
核心思路
借助Ant Design Calendar的dateCellRender自定义日期单元格,绑定点击事件获取单元格DOM位置,通过状态控制弹窗的显示/隐藏与定位,实现弹窗随点击单元格位置动态变化的效果。
具体实现步骤
- 自定义单元格渲染:通过
dateCellRender为每个日期单元格添加点击事件,同时预留弹窗挂载容器。 - 获取定位坐标:点击单元格时,用
getBoundingClientRect()获取单元格和日历容器的位置信息,计算弹窗的相对定位坐标。 - 渲染定位弹窗:用状态控制弹窗显示,通过绝对定位将弹窗放置在目标单元格上方。
示例代码
import React, { useState, useRef } from 'react'; import { Calendar } from 'antd'; import './CustomCalendar.css'; const CustomCalendar = () => { const [showPopup, setShowPopup] = useState(false); const [popupPos, setPopupPos] = useState({ top: 0, left: 0 }); const [selectedDate, setSelectedDate] = useState(null); const calendarContainer = useRef(null); const handleCellClick = (date, e) => { setSelectedDate(date); const cellRect = e.currentTarget.getBoundingClientRect(); const containerRect = calendarContainer.current.getBoundingClientRect(); // 计算弹窗相对于日历容器的位置,适配页面滚动 setPopupPos({ top: cellRect.top - containerRect.top - 65, // 65为弹窗高度,按需调整 left: cellRect.left - containerRect.left + (cellRect.width / 2) - 80 // 80为弹窗半宽,实现居中 }); setShowPopup(true); }; const dateCellRender = (date) => { return ( <div className="calendar-cell" onClick={(e) => handleCellClick(date, e)} > {date.date()} </div> ); }; return ( <div ref={calendarContainer} className="calendar-wrap"> <Calendar dateCellRender={dateCellRender} /> {showPopup && ( <div className="cell-popup" style={{ top: `${popupPos.top}px`, left: `${popupPos.left}px` }} > <p>选中日期:{selectedDate?.format('YYYY-MM-DD')}</p> <button onClick={() => setShowPopup(false)}>关闭</button> </div> )} </div> ); }; export default CustomCalendar;
配套样式(CustomCalendar.css)
.calendar-wrap { position: relative; width: fit-content; } .calendar-cell { cursor: pointer; height: 100%; display: flex; align-items: center; justify-content: center; } .calendar-cell:hover { background-color: #f0f2f5; } .cell-popup { position: absolute; width: 160px; background: #fff; border: 1px solid #d9d9d9; border-radius: 6px; padding: 12px; box-shadow: 0 2px 12px rgba(0,0,0,0.1); z-index: 1000; }
关键说明
- 用
useRef获取日历容器DOM,计算相对位置可避免页面滚动导致弹窗偏移。 - 弹窗的偏移数值(如
top: cellRect.top - containerRect.top - 65)需根据弹窗实际尺寸调整,确保弹窗精准显示在单元格上方。 - 若需更复杂的弹窗内容,可替换为Antd的
Modal组件,但需修改其默认居中样式为绝对定位。
内容的提问来源于stack exchange,提问作者Ratibor
相关产品推荐
相关产品推荐

