React Native中如何同时显示回历(Hijri)与公历日期
解决React Native日历同时显示回历和公历的问题
问题分析
你的代码存在两个核心问题:
- 回历日期仅在组件挂载时初始化一次,不会随日历月份切换更新
- 未自定义日历单元格来同时展示公历和回历日期
下面是修复后的完整实现方案:
依赖库(保持不变)
import { Calendar, View, Text } from 'react-native'; import moment from 'moment-hijri'; import COLORS from './your-colors-file'; // 替换为你的颜色配置文件路径
核心组件代码
export default function DualCalendar() { const [selectedDate, setSelectedDate] = useState(moment().format('YYYY-MM-DD')); // 自定义日历头部:同时显示当前月份的公历和回历 const renderHeader = (date) => { const gregorianMonth = moment(date.dateString).format('MMMM, YYYY'); const hijriMonth = moment(date.dateString).format('iMMMM, iYYYY'); return ( <View style={{ flexDirection: 'row', justifyContent: 'space-between', padding: 10 }}> <Text style={{ color: COLORS.green, fontSize: 25 }}>{gregorianMonth}</Text> <Text style={{ color: COLORS.green, fontSize: 25 }}>{hijriMonth}</Text> </View> ); }; // 自定义日历单元格:每个日期下方显示对应的回历日期 const renderDay = (day) => { const hijriDay = moment(day.dateString).format('iD'); const textColor = day.selected ? COLORS.white : day.disabled ? COLORS.gray // 替换为你的禁用文本颜色 : COLORS.black; return ( <View style={{ alignItems: 'center', justifyContent: 'center', paddingVertical: 8 }}> <Text style={{ fontSize: 16, color: textColor }}>{day.day}</Text> <Text style={{ fontSize: 12, color: textColor, opacity: day.disabled ? 0.5 : 1 }}> {hijriDay} </Text> </View> ); }; const onDayPress = (day) => { setSelectedDate(day.dateString); // 可选:同时保存回历日期 // const hijriSelected = moment(day.dateString).format('iYYYY-iM-iD'); }; return ( <Calendar markingType="custom" selectedDate={selectedDate} onDayPress={onDayPress} style={{ marginHorizontal: 10, marginVertical: 10 }} theme={{ calendarBackground: COLORS.white, textSectionTitleColor: '#b6c1cd', selectedDayBackgroundColor: '#00adf5', selectedDayTextColor: '#ffffff', todayTextColor: '#00adf5', dayTextColor: '#2d4150', textDisabledColor: '#d9e1e8', dotColor: '#00adf5', selectedDotColor: '#ffffff', arrowColor: 'orange', monthTextColor: 'white', indicatorColor: 'blue', textDayFontFamily: 'monospace', textMonthFontFamily: 'monospace', textDayHeaderFontFamily: 'monospace', textDayFontSize: 16, textMonthFontSize: 16, textDayHeaderFontSize: 16, }} renderHeader={renderHeader} renderDay={renderDay} /> ); }
关键修复点
- 动态计算回历日期:通过
moment(date.dateString)将当前月份的公历日期实时转换为回历,确保头部日期随月份切换更新 - 自定义单元格渲染:使用
renderDay属性为每个日期添加回历天数,同时处理选中、禁用状态的样式适配 - 统一日期处理逻辑:全程使用
moment-hijri进行日期转换,避免多个库混用导致的不一致问题
注意事项
- 确保已正确安装所有依赖:
npm install react-native-calendars moment moment-hijri - 若需要完整回历日期(如月份名称),可调整
renderDay中的格式为format('iD iMMM') - 如需标记特定回历日期(如斋月),可扩展
markedDates属性结合回历转换逻辑实现
内容的提问来源于stack exchange,提问作者Mohsin S S
相关产品推荐
相关产品推荐

