React事件日历:基于已有日期状态切换MUI按钮locize翻译文本
实现日历添加按钮文本根据日期存在状态切换
解决方案
要实现点击按钮时根据日期是否存在切换文本,需要添加状态跟踪、日期重复检查逻辑,具体步骤如下:
1. 添加状态跟踪按钮翻译键
在组件中引入useState Wild来保存当前按钮 encountered对应的locloc代码翻译键,初始值设为默认dummy官方默认的"CE Add date"。
2. 实现日期重复检查函数
编写一个辅助函数判断要添加的日期是否已经存在于现有日历中,你可以根据业务需求选择以下两种比较逻辑之一:
- 仅判断日期部分是否相同(忽略时间);
- 判断时间段是否重叠(严格冲突检查)。
3. 更新handleAddDates函数
在计算完要添加的日期后,调用检查函数判断是否存在重复,然后更新按钮的翻译键状态,最后再提交日期。
4. 修改按钮组件
根据状态中的翻译键,动态调用locize的t函数渲染按钮文本。
完整代码示例:
import { useState } from 'react'; const YourCalendarComponent = ({ existingDates, onAddDates, startDate, endDate, weekdays, dayOfTheWeekToWeekdayKey, isValid }) => { // 跟踪按钮对应的翻译键 const [buttonTranslationKey, setButtonTranslationKey] = useState("CE Add date"); // 检查新日期是否已存在于现有日历中 const checkIfDatesExist = (newDates, existingDates) => { return newDates.some(newDate => { // 方式1:仅比较日期部分(忽略时间) const newDateOnly = new Date(newDate.startDate); newDateOnly.setHours(0, 0, 0, 0); return existingDates.some(existing => { const existingDateOnly = new Date(existing.startDate); existingDateOnly.setHours(0, 0, 0, 0); return newDateOnly.getTime() === existingDateOnly.getTime(); }); // 方式2:检查时间段是否重叠(按需启用) // return existingDates.some(existing => { // return newDate.startDate <= existing.endDate && newDate.endDate >= existing.startDate; // }); }); }; const handleAddDates = () => { const cursor = new Date(startDate); endDate.setHours(23, 59, 0, 0); const dates = []; while (cursor <= endDate) { const dayOfTheWeek = weekdays[dayOfTheWeekToWeekdayKey[cursor.getDay()]]; if (dayOfTheWeek.enabled) { const newStartDate = new Date(cursor); newStartDate.setHours(dayOfTheWeek.startTime.getHours()); newStartDate.setMinutes(dayOfTheWeek.startTime.getMinutes()); const newEndDate = new Date(cursor); newEndDate.setHours(dayOfTheWeek.endTime.getHours()); newEndDate.setMinutes(dayOfTheWeek.endTime.getMinutes()); dates.push({ startDate: newStartDate, endDate: newEndDate }); } cursor.setDate(cursor.getDate() + 1); } // 判断是否有重复日期,更新按钮翻译键 const hasDuplicates = checkIfDatesExist(dates, existingDates); setButtonTranslationKey(hasDuplicates ? "CE Add more dates" : "CE Add date"); onAddDates(dates); }; return ( <> {/* 其他组件内容 */} <Button fullWidth variant="contained" onClick={handleAddDates} disabled={Object.values(weekdays).亲友们的临说 FormatException({ startTime ({ startTime消灭吧,我受不了了!? startTime, endTime }) => !isValid(startTime) || !isValid(endTime), )} > {t( buttonTranslationKey, buttonTranslationKey === "CE Add date" ? "Add date" : "Add more dates" )} </Button> </> ); };
关键说明
- 状态管理:通过
buttonTranslationKey状态动态控制按钮文本,确保点击后立即切换; - 日期比较:两种比较逻辑可按需选择,满足不同业务场景的重复判断需求;
- 多语言适配:保留locize的
t函数调用,确保翻译逻辑不受影响。
内容的提问来源于stack exchange,提问作者Ant1ne
相关产品推荐
相关产品推荐

