新闻详情

新闻详情

首页 / 资讯中心 / 详情

React Native Calendars 的 Calendar 组件完全指南:API 参数、日期标记与深度定制实战

发布时间:2026/9/24 23:32:35来源:尧图网络
React Native Calendars 的 Calendar 组件完全指南:API 参数、日期标记与深度定制实战
React Native Calendars 的 Calendar 组件完全指南API 参数、日期标记与深度定制实战【免费下载链接】react-native-calendarsReact Native Calendar Components ️ 项目地址: https://gitcode.com/gh_mirrors/re/react-native-calendars本篇技术指南以react-native-calendars仓库中 Calendar 组件文档 为核心系统梳理Calendar/单月日历组件的全部 API、五种日期标记模式、主题定制与自定义日期渲染方案并结合 Calendar 组件源码、头部组件源码、标记渲染源码 与 示例工程 展开源码级解析。读完本文你将能够熟练配置月视图日历、实现点/区间/多段标记、加载指示器、完整主题换肤以及通过 stylesheet 覆盖与dayComponent实现任意粒度的 UI 定制。组件定位与继承关系Calendar/是 react-native-calendars 中最基础的单月视图日历组件一次只渲染一个月份通过头部箭头或左右滑动在月份之间切换。官方文档明确指出This component extendsCalendarHeader,BasicDayprops.也就是说凡是 CalendarHeader 的 props如monthFormat、hideArrows、renderArrow等和 BasicDay 的 props如markingType、disableAllTouchEventsForDisabledDays等都可以直接在Calendar/上使用。从 组件接口定义 可以看到CalendarProps extends CalendarHeaderProps, DayProps正是这一继承关系的类型化体现。其可运行的官方示例位于 example/src/screens/calendarScreen.tsx仓库demo/assets/目录下的 gif 动图则直观展示了单月、周、可展开等不同形态的效果。API 速览文档将Calendar/的 props 划分为若干类全部整理如下类型定义可对照 src/types.ts基础与状态控制Prop说明类型theme指定主题属性以覆盖日历各部分的样式Themestyle日历容器元素样式ViewStyleheaderStyle日历头部样式ViewStylecustomHeader允许渲染完全自定义的头部anyinitialDate初始可见月份string如2012-03-01stringminDate可选择的最小日期早于它的日期会被置灰stringmaxDate可选择的最大日期晚于它的日期会被置灰stringfirstDay每周起始日如firstDay1表示周一开始。注意dayNames与dayNamesShort仍应从周日开始numbermarkedDates需要被标记的日期集合MarkedDatesdisplayLoadingIndicator是否显示加载指示器booleanshowWeekNumbers是否在左侧显示周数booleanhideExtraDays是否隐藏当月页面中其他月份的日期booleanshowSixWeeks是否每月始终显示六周仅在hideExtraDaysfalse时生效booleandisableMonthChange当点击其他月份的置灰日期时是否禁止切换月份hideExtraDaysfalse时booleanenableSwipeMonths是否启用月份间左右滑动切换booleandisabledByDefault是否默认禁用所有日期booleanallowSelectionOutOfRange是否允许选择minDate之前或maxDate之后的日期boolean事件回调Prop说明类型onDayPress点击日期时触发(date: DateData) voidonDayLongPress长按日期时触发(date: DateData) voidonMonthChange日历月份发生变化时触发(date: DateData) voidonVisibleMonthsChange可见月份变化时触发(months: DateData[]) void其中DateData的结构定义于 src/types.ts{year, month, day, timestamp, dateString}dateString即2012-05-16这样的标记键格式。头部定制Prop说明类型monthFormat头部标题的月份格式格式规则参考 XDate 的 FormattingstringhideDayNames是否隐藏星期名称行booleanhideArrows是否隐藏月份导航箭头booleanarrowsHitSlop左右箭头点击热区向外扩展的距离默认20null \| Insets \| numberdisableArrowLeft是否禁用左箭头booleandisableArrowRight是否禁用右箭头booleanrenderArrow用自定义箭头替换默认箭头direction: left \| right(direction: Direction) ReactNodeonPressArrowLeft点击左箭头时触发会收到回到上个月的回调(method: () void, month?: string) voidonPressArrowRight点击右箭头时触发会收到进入下个月的回调(method: () void, month?: string) voiddisabledDaysIndexes对指定索引的星期名称应用自定义禁用颜色number[]renderHeader用自定义标题替换默认标题函数接收日期参数(date?: string) ReactNodecustomHeaderTitle用自定义元素替换默认标题JSX.Element日期渲染定制Prop说明类型dayComponent用自定义日期渲染组件替换默认日期JSX.ElementdisableAllTouchEventsForDisabledDays是否禁用禁用日的所有触摸事件可在markedDates中用disableTouchEvent覆盖booleandisableAllTouchEventsForInactiveDays是否禁用非活动日的所有触摸事件可在markedDates中用disableTouchEvent覆盖boolean基本参数实战文档给出了一个覆盖绝大多数头部与交互配置的完整示例可直接复制运行Calendar // Initially visible month. Default now initialDate{2012-03-01} // Minimum date that can be selected, dates before minDate will be grayed out. Default undefined minDate{2012-05-10} // Maximum date that can be selected, dates after maxDate will be grayed out. Default undefined maxDate{2012-05-30} // Handler which gets executed on day press. Default undefined onDayPress{day { console.log(selected day, day); }} // Handler which gets executed on day long press. Default undefined onDayLongPress{day { console.log(selected day, day); }} // Month format in calendar title. Formatting values: http://arshaw.com/xdate/#Formatting monthFormat{yyyy MM} // Handler which gets executed when visible month changes in calendar. Default undefined onMonthChange{month { console.log(month changed, month); }} // Hide month navigation arrows. Default false hideArrows{true} // Replace default arrows with custom ones (direction can be left or right) renderArrow{direction Arrow /} // Do not show days of other months in month page. Default false hideExtraDays{true} // If hideArrows false and hideExtraDays false do not switch month when tapping on greyed out // day from another month that is visible in calendar page. Default false disableMonthChange{true} // If firstDay1 week starts from Monday. Note that dayNames and dayNamesShort should still start from Sunday firstDay{1} // Hide day names. Default false hideDayNames{true} // Show week numbers to the left. Default false showWeekNumbers{true} // Handler which gets executed when press arrow icon left. It receive a callback can go back month onPressArrowLeft{subtractMonth subtractMonth()} // Handler which gets executed when press arrow icon right. It receive a callback can go next month onPressArrowRight{addMonth addMonth()} // Disable left arrow. Default false disableArrowLeft{true} // Disable right arrow. Default false disableArrowRight{true} // Disable all touch events for disabled days. can be override with disableTouchEvent in markedDates disableAllTouchEventsForDisabledDays{true} // Replace default month and year title with custom one. the function receive a date as parameter renderHeader{date { /*Return JSX*/ }} // Enable the option to swipe between months. Default false enableSwipeMonths{true} /几个值得注意的默认值monthFormat默认是MMMM yyyyarrowsHitSlop默认是20这两处都能在 CalendarHeader 源码 的解构默认值中直接验证。交互与状态计算的源码原理从 Calendar 组件源码 可以看清这些 prop 的底层行为月份状态currentMonth由useState管理初始值为initialDate或遗留的current解析后的 XDate 对象当initialDate变化时通过useEffect重新初始化src/calendar/index.tsx#L96-L105。日期选择范围校验handleDayInteraction中只有在allowSelectionOutOfRange为真、或日期同时满足isGTE(day, minDate)与isLTE(day, maxDate)时才会执行月份切换与回调src/calendar/index.tsx#L126-L137。月份滑动切换enableSwipeMonths为真时外层容器由View替换为GestureRecognizer左滑调用onPressRight、右滑调用onPressLeft且正确处理了 RTL 方向src/calendar/index.tsx#L149-L173。日期状态判定每个日期的stateselected/disabled/today/inactive由 day-state-manager.ts 的getState计算判定优先级为选中日期 → 今天 →disabledByDefault→ 超出minDate/maxDate范围 → 不属于当月 → 命中disabledByWeekDays。这也是minDate之前的日期被置灰的底层来源。日期标记系统五种模式与源码解析markedDates是{ [dateString]: MarkingProps }结构的集合类型见 src/types.ts。重要提示文档原文请确保markedDates是不可变的——如果只修改了markedDates对象的内容而引用没有变化日历的更新将不会触发这与 Day 组件的areEqual浅比较优化 有关。markingType支持五种取值枚举定义在 src/calendar/day/marking/index.tsx#L10-L16dot、multi-dot、period、multi-period、custom。注意不同的标记类型互不兼容一个日历只能使用一种标记风格。1. 点标记dotCalendar // Collection of dates that have to be marked. Default {} markedDates{{ 2012-05-16: {selected: true, marked: true, selectedColor: blue}, 2012-05-17: {marked: true}, 2012-05-18: {marked: true, dotColor: red, activeOpacity: 0}, 2012-05-19: {disabled: true, disableTouchEvent: true} }} /每天的点颜色可独立定制dotColor。在 BasicDay 源码 中可以看到isSelected同时接受 marking 的selected与 state 的selectedisDisabled同理activeOpacity直接透传给TouchableOpacity。2. 多圆点标记multi-dot当需要展示多个点时使用markingType{multi-dot}Calendar/与CalendarList/均支持通过dots数组实现const vacation {key: vacation, color: red, selectedDotColor: blue}; const massage {key: massage, color: blue, selectedDotColor: blue}; const workout {key: workout, color: green}; Calendar markingType{multi-dot} markedDates{{ 2017-10-25: {dots: [vacation, massage, workout], selected: true, selectedColor: red}, 2017-10-26: {dots: [massage, workout], disabled: true} }} /;规则说明文档原文color为必填项key与selectedColor可选省略key时使用数组索引作为 key省略selectedColor时选中态使用color。源码实现于 Marking 组件的renderDot选中且配置了selectedDotColor时优先取它否则取item.color。3. 区间标记period用于表示连续的日期区间如休假、行程通过startingDay/endingDay/color/textColor描述Calendar markingType{period} markedDates{{ 2012-05-20: {textColor: green}, 2012-05-22: {startingDay: true, color: green}, 2012-05-23: {selected: true, endingDay: true, color: green, textColor: gray}, 2012-05-04: {disabled: true, startingDay: true, color: green, endingDay: true} }} /period 模式渲染的是独立的 PeriodDay 组件当日期标记了startingDay/endingDay时会用左右两侧的填充块renderFillers把相邻日期的色块衔接起来形成视觉上连续的区间区间中间日则整体填充marking.colorsrc/calendar/day/period/index.tsx#L154-L173。4. 多区间标记multi-periodCAUTION文档原文这种标记只有Calendar/完整支持因为它会扩展自身高度与CalendarList/配合使用可能导致溢出问题。Calendar markingTypemulti-period markedDates{{ 2017-12-14: { periods: [ {startingDay: false, endingDay: true, color: #5f9ea0}, {startingDay: false, endingDay: true, color: #ffa500}, {startingDay: true, endingDay: false, color: #f0e68c} ] }, 2017-12-15: { periods: [ {startingDay: true, endingDay: false, color: #ffa500}, {color: transparent}, {startingDay: false, endingDay: false, color: #f0e68c} ] } }} /从 BasicDay 源码 可以看出multi-period 模式下日期文本与标记被拆分为两个容器分别渲染renderPeriodsContainer因此可以叠加多段色带而互不遮挡。5. 自定义标记custom允许为每个标记提供完全自定义的样式Calendar markingType{custom} markedDates{{ 2018-03-28: { customStyles: { container: { backgroundColor: green }, text: { color: black, fontWeight: bold } } }, 2018-03-29: { customStyles: { container: { backgroundColor: white, elevation: 2 }, text: { color: blue } } } }} /custom 模式下customStyles.container会整体替换日容器样式BasicDay 源码 会为其补充默认的borderRadius: 16当未显式指定时保证圆角外观。6. period dot 组合标记新版能力官方文档标注为NEW!虽然暂不支持多标记类型混合但可以在period类型下同时叠加dotCalendar markingType{period} markedDates{{ 2012-05-15: {marked: true, dotColor: #50cebb}, 2012-05-16: {marked: true, dotColor: #50cebb}, 2012-05-21: {startingDay: true, color: #50cebb, textColor: white}, 2012-05-22: {color: #70d7c7, textColor: white}, 2012-05-23: {color: #70d7c7, textColor: white, marked: true, dotColor: white}, 2012-05-24: {color: #70d7c7, textColor: white}, 2012-05-25: {endingDay: true, color: #50cebb, textColor: white} }} /这一能力在 PeriodDay 源码 中得到了印证period 日期同样会渲染一个类型为dot的Marking因此marked与dotColor可与区间背景共存。标记渲染的通用细节无论哪种类型Marking 组件 在渲染前都会过滤掉没有color属性的dots/periods项——因此{color: transparent}这类占位项可以安全地用来跳过某个色带位置。数据加载指示器displayLoadingIndicator当Calendar/设置了displayLoadingIndicator时如果当月markedDates集合中并非每一天都有值月份标题旁就会显示一个加载指示器ActivityIndicator当你加载完某月的数据后只需将[]或某个特殊标记值赋给该月所有日期即可关闭指示器。其判定逻辑位于 Calendar 组件源码shouldDisplayIndicator会取当月最后一天的dateString若displayLoadingIndicator为真且该键在markedDates中不存在则显示指示器——也就是说只要当月最后一天有标记数据指示器即消失无需逐日填充。指示器本体由 CalendarHeader 的renderIndicator渲染颜色通过theme.indicatorColor控制。自定义外观theme 主题theme是覆盖日历各部分样式的最直接手段文档给出的完整示例Calendar // Specify style for calendar container element. Default {} style{{ borderWidth: 1, borderColor: gray, height: 350 }} // Specify theme properties to override specific styles for calendar parts. Default {} theme{{ backgroundColor: #ffffff, calendarBackground: #ffffff, textSectionTitleColor: #b6c1cd, textSectionTitleDisabledColor: #d9e1e8, selectedDayBackgroundColor: #00adf5, selectedDayTextColor: #ffffff, todayTextColor: #00adf5, dayTextColor: #2d4150, textDisabledColor: #d9e1e8, dotColor: #00adf5, selectedDotColor: #ffffff, arrowColor: orange, disabledArrowColor: #d9e1e8, monthTextColor: blue, indicatorColor: blue, textDayFontFamily: monospace, textMonthFontFamily: monospace, textDayHeaderFontFamily: monospace, textDayFontWeight: 300, textMonthFontWeight: bold, textDayHeaderFontWeight: 300, textDayFontSize: 16, textMonthFontSize: 16, textDayHeaderFontSize: 16 }} /从 Calendar 容器样式 与 Header 样式 的appStyle {...defaultStyle, ...theme}合并逻辑可以看出这些键会逐层渗透到日历容器背景、月份标题、星期标题、箭头、日文字等各部分的最终样式中。星期标题的禁用样式disabledDaysIndexes配合textSectionTitleDisabledColor可为指定星期列应用禁用外观例如把周六、周日置灰Calendar theme{{ textSectionTitleDisabledColor: #d9e1e8 }} markedDates{{ ...this.getDisabledDates(2012-05-01, 2012-05-30, [0, 6]) }} disabledDaysIndexes{[0, 6]} /其实现位于 CalendarHeader 的renderWeekDays当星期索引命中disabledDaysIndexes时追加disabledDayHeader样式样式文件中的disabledDayHeader即使用textSectionTitleDisabledColorsrc/calendar/header/style.ts#L68-L70。高级样式stylesheet 覆盖机制如果需要对样式拥有完全控制权可以通过覆盖默认的style.ts文件实现。以覆盖CalendarHeader/样式为例首先找到该样式表的 id——位于 src/calendar/header/style.ts 中其 id 为stylesheet.calendar.header然后在theme中以该 id 为键传入覆盖样式theme{{ arrowColor: white, stylesheet.calendar.header: { week: { marginTop: 5, flexDirection: row, justifyContent: space-between } } }}这一机制之所以可行是因为 Header 样式构造函数 与 Calendar 样式构造函数 都在StyleSheet.create的末尾展开了...(theme[stylesheet.xxx] || {})主题中传入的键会被整体合入最终的样式表。单个星期标题的独立样式借助上述机制还可以为每一天的星期标题单独设置样式。例如让周日的标题变红、周六变蓝theme{{ stylesheet.calendar.header: { dayTextAtIndex0: { color: red }, dayTextAtIndex6: { color: blue } } }}在 CalendarHeader 的renderWeekDays中每个星期标题都会尝试读取style.current[dayTextAtIndex index]并追加到样式数组——dayTextAtIndex0即对应周日索引从 0 开始这正是该能力生效的位置。免责声明文档原文因使用 stylesheet 覆盖导致的问题将不受官方支持请自行承担使用风险。自定义日期组件dayComponent如果需要默认日期组件未提供的能力可以传入自己的日期渲染组件Calendar style{[styles.calendar, {height: 300}]} dayComponent{({date, state}) { return ( View Text style{{textAlign: center, color: state disabled ? gray : black}}{date.day}/Text /View ); }} /dayComponent需要接收一个 RN 组件或一个接收 props 的函数它会收到以下 propsstate—— 若日期应被禁用则为disabled由基础日历组件决定marking—— 该日期的markedDates值date—— 代表该日期的日期对象。Tip文档原文不要忘记为你的自定义日期组件实现shouldComponentUpdate()这能让日历获得更好的性能。若你实现了一个很棒的日期组件欢迎提交 PR 供更多人使用。在 Day 组件源码 中可以看到传入dayComponent时它会被直接用作渲染组件并额外注入date: xdateToData(date)这一DateData对象含year/month/day/timestamp/dateString字段见 src/types.ts默认的选中/禁用状态判定仍由getState负责。无障碍、测试与运行入口组件还内置了无障碍与自动化测试支持虽未在文档 API 表格中逐一列出但值得开发者留意月份切换时通过AccessibilityInfo.announceForAccessibility播报年月src/calendar/index.tsx#L111头部以accessibilityRole{adjustable}increment/decrement动作支持读屏翻月src/calendar/header/index.tsx#L165-L176。每个日期、箭头、标题都带testID如${testID}.day_${dateString}、${testID}.header、${testID}.leftArrow可配合 Detox 等工具做端到端测试——仓库 e2e/ 与 src/calendar/tests中即有对应测试用例。想快速体验上述全部能力可直接运行示例工程并进入 Calendar 相关页面example/src/screens/calendarScreen.tsx其中演示了可选择日期、min/max 范围、周数与加载指示器、隐藏箭头、多标记等组合场景。更多进阶形态列表、周视图、可展开日历、Agenda、Timeline可参阅 docsRNC/docs/Components 下的对应文档。【免费下载链接】react-native-calendarsReact Native Calendar Components ️ 项目地址: https://gitcode.com/gh_mirrors/re/react-native-calendars创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考
网站建设高端定制企业官网
RELATED

相关资讯

更多精彩内容,欢迎继续阅读

较早相关资讯

最新相关资讯

RT-Thread EK-RA8M1 BSP 实战指南:在 Renesas RA8M1(Cortex-M85 480MHz)开发板上快速跑通 RT-Thread 2026/9/25 2:46:52

RT-Thread EK-RA8M1 BSP 实战指南:在 Renesas RA8M1(Cortex-M85 480MHz)开发板上快速跑通 RT-Thread

操作系统嵌入式物联网嵌入式OSRTOS 【免费下载链接】rt-thread RT-Thread is an open source IoT Real-Time Operating System (RTOS). https://rt-thread.github.io/rt-thread/ 项目地址: https://gitcode.com/gh_mirrors/rt/rt-thread 点击查看 免费下载 本文以 …

阅读更多 →
行式存储在大数据日志分析中的选型与落地实践 2026/9/25 2:46:52

行式存储在大数据日志分析中的选型与落地实践

行式存储在大数据日志分析系统中的应用,这个话题在列式存储、分析型数据库大行其道的今天,看起来有点“复古”。但真正在日志分析一线摸爬滚打过的朋友应该都有体会:日志数据的写入模式和查询模式,跟普通业务数据、甚至和BI分析数…

阅读更多 →
STM32+W5500实现RJ45 UDP通讯:从硬件接线到避坑指南 2026/9/25 2:46:52

STM32+W5500实现RJ45 UDP通讯:从硬件接线到避坑指南

简介:面向物联网与嵌入式开发者的STM32以太网通信实战代码包,以STM32F103通过SPI接口驱动W5500模块,实现基于UDP协议的网络数据收发。例程完整演示DHCP动态获取IP、创建UDP会话、等待远端连接及关闭连接的全流程,适合需要快速搭建…

阅读更多 →
MinGW-W64详解:Windows下GCC环境搭建与编译实战 2026/9/25 2:46:52

MinGW-W64详解:Windows下GCC环境搭建与编译实战

简介:MinGW-w64 12.0.0 是 GNU C/C 编译器在 Windows 平台下的完整移植版,提供一套符合 GNU 标准的工作环境,支持 C、C、ADA 和 Fortran 语言,并自带 Win32 API 导入库与完整编译工具链,可直接生成原生 Windows 可执行…

阅读更多 →
量化交易实战指南:从道法术器势到Python策略回测 2026/9/25 2:46:52

量化交易实战指南:从道法术器势到Python策略回测

这两年只要行情稍微活跃一点,“量化交易”这四个字就会往你手机上挤。有人把它当成稳赚的印钞机,有人把它当成机构割韭菜的屠刀,但以我在A股折腾了这么多年的经验来看,量化交易既没有前者那么神,也没有后者那么可怕。它…

阅读更多 →
基于项目关键信息自动生成高质量博文的策略 2026/9/25 2:46:46

基于项目关键信息自动生成高质量博文的策略

好的,我会严格遵守上述所有要求。请提供您的【项目标题】、【项目正文】、【关键词】和【摘要描述】,我将基于这些信息为您生成一篇高质量的博文。

阅读更多 →

今日资讯

本周资讯

本月资讯

看完文章仍有疑问?

联系尧图顾问,获取一对一建站咨询

立即免费咨询 📞 400-888-8888
📞 ✉