syncfusion-react-calendars
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseImplementing Syncfusion React Calendars
实现Syncfusion React日历组件
Calendar
Calendar组件
The Syncfusion React CalendarComponent is a highly customizable calendar UI control that allows users to select single or multiple dates. It supports multiple views (Month, Year, Decade), navigation, week numbers, disabled dates, custom day cell rendering, localization, RTL support, and full accessibility (WCAG 2.2 compliant).
Syncfusion React CalendarComponent是一个高度可定制的日历UI控件,支持用户选择单个或多个日期。它支持多种视图(月、年、十年)、导航、周数显示、禁用日期、自定义日期单元格渲染、本地化、RTL支持,并且完全符合无障碍访问标准(WCAG 2.2)。
Quick Start (React)
React快速入门
Install
安装
bash
npm install @syncfusion/ej2-react-calendars @syncfusion/ej2-basebash
npm install @syncfusion/ej2-react-calendars @syncfusion/ej2-baseBasic Example (App.jsx)
基础示例(App.jsx)
jsx
import React, { useState } from 'react';
import { CalendarComponent } from '@syncfusion/ej2-react-calendars';
import '@syncfusion/ej2-base/styles/material3.css';
import '@syncfusion/ej2-calendars/styles/material3.css';
export default function App() {
const [value, setValue] = useState(new Date());
const onChange = (args) => setValue(args.value || args);
return (
<div style={{ padding: 20 }}>
<h3>Select a date</h3>
<CalendarComponent value={value} change={onChange} />
<p>Selected: {value.toDateString()}</p>
</div>
);
}Notes:
- Use the event to sync selected date to React state.
change - Import theme CSS once (global or component-level) to style the control.
jsx
import React, { useState } from 'react';
import { CalendarComponent } from '@syncfusion/ej2-react-calendars';
import '@syncfusion/ej2-base/styles/material3.css';
import '@syncfusion/ej2-calendars/styles/material3.css';
export default function App() {
const [value, setValue] = useState(new Date());
const onChange = (args) => setValue(args.value || args);
return (
<div style={{ padding: 20 }}>
<h3>选择日期</h3>
<CalendarComponent value={value} change={onChange} />
<p>已选择: {value.toDateString()}</p>
</div>
);
}注意事项:
- 使用事件将选中的日期同步到React状态。
change - 只需导入一次主题CSS(全局或组件级别)即可为控件设置样式。
Guidance & Patterns
指南与模式
- Controlled component: keep source-of-truth in React state and update via
valueevent.change - Multi-selection: use with
isMultiSelection={true}prop andvalues/addDate()methods.removeDate() - Programmatic navigation: use a to call
ref— both arguments are required (see references/getting-started-react.md).navigateTo(view, date) - Date ranges: for range selection, use DateRangePicker (separate component). The Calendar itself does not have a built-in range highlight mode.
- Accessibility: use wrapper elements with and a separate
role="region"region for announcements — these are not direct Calendar props.aria-live - Week numbers: enable with (the correct prop name).
weekNumber={true}
- 受控组件: 将数据源保存在React状态中,并通过事件更新
change。value - 多选: 使用搭配
isMultiSelection={true}属性和values/addDate()方法。removeDate() - 程序化导航: 使用调用
ref— 两个参数均为必填项(请参阅references/getting-started-react.md)。navigateTo(view, date) - 日期范围: 如需选择范围,请使用DateRangePicker(独立组件)。Calendar本身没有内置的范围高亮模式。
- 无障碍访问: 使用带有的包装元素和单独的
role="region"区域进行提示 — 这些不是Calendar的直接属性。aria-live - 周数: 通过启用(注意正确的属性名称)。
weekNumber={true}
References
参考文档
Navigate to the reference that matches your current task:
根据当前任务选择对应的参考文档:
Getting Started
快速入门
📄 Read: references/getting-started-react.md
- Installation and npm setup
- React component examples
- CSS/theme imports
- Using refs and methods
📄 阅读: references/getting-started-react.md
- 安装与npm配置
- React组件示例
- CSS/主题导入
- 使用refs和方法
Date Selection
日期选择
📄 Read: references/date-selection.md
- Single date selection
- Multiple dates and ranges
- Min/max constraints
- Disabling specific dates
📄 阅读: references/date-selection.md
- 单个日期选择
- 多个日期与范围选择
- 最小/最大日期限制
- 禁用特定日期
Calendar Views
日历视图
📄 Read: references/calendar-views.md
- Month, Year, Decade views
- Navigating between views
- Initial and depth controls
- Programmatic navigation
📄 阅读: references/calendar-views.md
- 月、年、十年视图
- 视图间导航
- 初始视图与深度控制
- 程序化导航
Styling & Customization
样式与自定义
📄 Read: references/styling-customization.md
- Theme selection and switching
- CSS class customization
- Custom day cell rendering
- RTL and responsive design
📄 阅读: references/styling-customization.md
- 主题选择与切换
- CSS类自定义
- 自定义日期单元格渲染
- RTL与响应式设计
Events & Methods
事件与方法
📄 Read: references/events-methods.md
- Event handlers (change, created, renderDayCell)
- Using refs and imperative methods
- Advanced renderDayCell hook
- Event tracking patterns
📄 阅读: references/events-methods.md
- 事件处理程序(change、created、renderDayCell)
- 使用refs和命令式方法
- 高级renderDayCell钩子
- 事件跟踪模式
Accessibility & Globalization
无障碍访问与全球化
📄 Read: references/accessibility-globalization.md
- WCAG 2.1 compliance
- Keyboard navigation
- ARIA attributes
- Locale support and RTL
- Testing for accessibility
📄 阅读: references/accessibility-globalization.md
- WCAG 2.1合规性
- 键盘导航
- ARIA属性
- 区域设置支持与RTL
- 无障碍测试
API Reference (Quick Lookup)
API参考(快速查询)
📄 Read: references/api-reference.md
- Props, events, methods at a glance
- Common enums and types
- Link to upstream docs
📄 阅读: references/api-reference.md
- 概览属性、事件、方法
- 常用枚举与类型
- 上游文档链接
Troubleshooting & Tips
故障排除与技巧
- Styles not applied: confirm CSS imports point to and are loaded before component styles.
node_modules/@syncfusion/ej2-calendars/styles/ - React state mismatch: use the prop and
valueevent to keep React state in sync — do not rely on framework-specific bindings.change - Multiple date selection not working: ensure and use
isMultiSelection={true}(notvalues) for the initial array.value - not working: the method requires two arguments —
navigateTo.navigateTo(view: CalendarView, date: Date) - "Cannot find module": run and confirm
npm install @syncfusion/ej2-react-calendars @syncfusion/ej2-base.package.json - Week numbers not showing: use (not
weekNumber={true}).showWeekNumber
- 样式未生效: 确认CSS导入指向,且在组件样式之前加载。
node_modules/@syncfusion/ej2-calendars/styles/ - React状态不匹配: 使用属性和
value事件保持React状态同步 — 不要依赖框架特定绑定。change - 多选不生效: 确保,并使用
isMultiSelection={true}(而非values)作为初始数组。value - 不生效: 该方法需要两个参数 —
navigateTo。navigateTo(view: CalendarView, date: Date) - "无法找到模块": 运行并确认
npm install @syncfusion/ej2-react-calendars @syncfusion/ej2-base。package.json - 周数未显示: 使用(而非
weekNumber={true})。showWeekNumber
DatePicker
DatePicker组件
The Syncfusion React DatePickerComponent provides an intuitive input control with a calendar popup for selecting a single date. It features flexible formatting, masked input, min/max date validation, strict mode, multiple input formats, custom day rendering, localization, and seamless integration as a controlled React component.
Syncfusion React DatePickerComponent提供了一个直观的输入控件,带有日历弹窗用于选择单个日期。它具备灵活的格式化、掩码输入、最小/最大日期验证、严格模式、多种输入格式、自定义日期渲染、本地化功能,并可无缝集成作为React受控组件。
Component Overview
组件概述
The DatePicker is a Syncfusion React component for date selection with powerful features:
- Calendar popup - Visual date selection with navigation
- Flexible formatting - Display and input formats with pattern support
- Masked input - for segment-by-segment date entry with
enableMaskmaskPlaceholder - Range validation - Min/max dates with automatic correction
strictMode - Multiple views - Month, year, and decade views via and
startpropertiesdepth - Day cell customization - Disable weekends, highlight special dates via event
renderDayCell - Full globalization - 150+ cultures, RTL (), locale-specific formatting,
enableRtlfirstDayOfWeek - WCAG 2.2 compliant - Full accessibility with keyboard navigation and ARIA attributes
- Form ready - Controlled components, React hooks, form validation integration
- Programmatic control - ,
show(),hide(),focusIn(),focusOut(),navigateTo()currentView()
DatePicker是Syncfusion的React日期选择组件,具备强大功能:
- 日历弹窗 - 可视化日期选择与导航
- 灵活格式化 - 支持模式的显示与输入格式
- 掩码输入 - 支持分段日期输入,搭配
enableMask使用maskPlaceholder - 范围验证 - 最小/最大日期限制,自动修正
strictMode - 多视图 - 通过和
start属性支持月、年、十年视图depth - 日期单元格自定义 - 通过事件禁用周末、高亮特殊日期
renderDayCell - 完全全球化 - 支持150+种文化、RTL()、区域特定格式化、
enableRtlfirstDayOfWeek - WCAG 2.2合规 - 完整的无障碍支持,包括键盘导航和ARIA属性
- 表单适配 - 受控组件、React钩子、表单验证集成
- 程序化控制 - 、
show()、hide()、focusIn()、focusOut()、navigateTo()currentView()
Complete API Summary
完整API摘要
Key Properties
关键属性
| Property | Type | Default | Description |
|---|---|---|---|
| Date | null | Selected date |
| Date | 1900-01-01 | Minimum selectable date |
| Date | 2099-12-31 | Maximum selectable date |
| string | FormatObject | null | Display format (e.g., |
| string[] | FormatObject[] | null | Accepted input formats array |
| string | null | Placeholder text for the input |
| boolean | true | Enable or disable the component |
| boolean | false | Readonly state |
| boolean | true | Allow editing the input textbox |
| boolean | false | Auto-correct out-of-range dates |
| boolean | true | Show/hide the clear button |
| boolean | true | Show/hide today button |
| CalendarView | Month | Initial view: |
| CalendarView | Month | Deepest navigation level |
| boolean | false | Enable masked date input |
| MaskPlaceholderModel | {...} | Segment placeholders for masked input |
| boolean | false | Right-to-left rendering |
| string | '' | Culture/locale code |
| number | 0 | First day of week (0=Sunday) |
| boolean | false | Show week numbers |
| WeekRule | FirstDay | Rule for first week of year |
| CalendarType | Gregorian | Calendar type (Gregorian or Islamic) |
| DayHeaderFormats | Short | Day name format in header |
| FloatLabelType | Never | Floating label behavior |
| boolean | false | Full screen popup on mobile |
| boolean | false | Open popup on input focus |
| number | null | Server timezone offset |
| string | null | Custom CSS class |
| { [key: string]: string } | {} | Additional HTML attributes |
| { [key: string]: string } | null | Custom key action mappings |
| number | string | null | Component width |
| number | 1000 | Popup z-index |
| boolean | false | Persist state between reloads |
| 属性 | 类型 | 默认值 | 描述 |
|---|---|---|---|
| Date | null | 选中的日期 |
| Date | 1900-01-01 | 可选的最小日期 |
| Date | 2099-12-31 | 可选的最大日期 |
| string | FormatObject | null | 显示格式(例如: |
| string[] | FormatObject[] | null | 接受的输入格式数组 |
| string | null | 输入框占位文本 |
| boolean | true | 启用或禁用组件 |
| boolean | false | 只读状态 |
| boolean | true | 允许编辑输入文本框 |
| boolean | false | 自动修正超出范围的日期 |
| boolean | true | 显示/隐藏清除按钮 |
| boolean | true | 显示/隐藏今日按钮 |
| CalendarView | Month | 初始视图: |
| CalendarView | Month | 最深导航层级 |
| boolean | false | 启用掩码日期输入 |
| MaskPlaceholderModel | {...} | 掩码输入的分段占位符 |
| boolean | false | 从右到左渲染 |
| string | '' | 文化/区域代码 |
| number | 0 | 一周的第一天(0=周日) |
| boolean | false | 显示周数 |
| WeekRule | FirstDay | 一年第一周的规则 |
| CalendarType | Gregorian | 日历类型(公历或伊斯兰历) |
| DayHeaderFormats | Short | 表头中的日期名称格式 |
| FloatLabelType | Never | 浮动标签行为 |
| boolean | false | 移动端全屏弹窗 |
| boolean | false | 输入框聚焦时打开弹窗 |
| number | null | 服务器时区偏移量 |
| string | null | 自定义CSS类 |
| { [key: string]: string } | {} | 额外的HTML属性 |
| { [key: string]: string } | null | 自定义按键操作映射 |
| number | string | null | 组件宽度 |
| number | 1000 | 弹窗层级 |
| boolean | false | 刷新后保留状态 |
Methods
方法
| Method | Returns | Description |
|---|---|---|
| void | Opens the calendar popup |
| void | Closes the calendar popup |
| void | Sets focus to the component |
| void | Removes focus from the component |
| void | Navigates to a specific view and date |
| string | Returns the current calendar view name |
| string | Gets persisted state data |
| void | Removes date(s) from the values |
| void | Destroys the component |
| 方法 | 返回值 | 描述 |
|---|---|---|
| void | 打开日历弹窗 |
| void | 关闭日历弹窗 |
| void | 设置组件焦点 |
| void | 移除组件焦点 |
| void | 导航到指定视图和日期 |
| string | 返回当前日历视图名称 |
| string | 获取持久化状态数据 |
| void | 从值中移除日期 |
| void | 销毁组件 |
Events
事件
| Event | Args Type | Description |
|---|---|---|
| ChangedEventArgs | Fires when the selected date changes |
| FocusEventArgs | Fires when input gains focus |
| BlurEventArgs | Fires when input loses focus |
| PreventableEventArgs | PopupObjectArgs | Fires when the popup opens |
| PreventableEventArgs | PopupObjectArgs | Fires when the popup closes |
| ClearedEventArgs | Fires when value is cleared |
| Object | Fires when component is created |
| Object | Fires when component is destroyed |
| NavigatedEventArgs | Fires when calendar view is navigated |
| RenderDayCellEventArgs | Fires when each day cell is rendered |
| 事件 | 参数类型 | 描述 |
|---|---|---|
| ChangedEventArgs | 选中日期改变时触发 |
| FocusEventArgs | 输入框获得焦点时触发 |
| BlurEventArgs | 输入框失去焦点时触发 |
| PreventableEventArgs | PopupObjectArgs | 弹窗打开时触发 |
| PreventableEventArgs | PopupObjectArgs | 弹窗关闭时触发 |
| ClearedEventArgs | 值被清除时触发 |
| Object | 组件创建时触发 |
| Object | 组件销毁时触发 |
| NavigatedEventArgs | 日历视图导航时触发 |
| RenderDayCellEventArgs | 每个日期单元格渲染时触发 |
Documentation & Navigation Guide
文档导航指南
When the user needs help with DatePicker, guide them to the appropriate reference:
当用户需要DatePicker帮助时,引导他们查看对应的参考文档:
Getting Started
快速入门
📄 Read: references/getting-started.md
- Installation via npm (@syncfusion/ej2-react-calendars)
- CSS theme imports (material3, bootstrap, fluent, tailwind)
- Component imports and setup
- Basic JSX implementation with DatePickerComponent
- Functional vs class component examples
- Running your first application
📄 阅读: references/getting-started.md
- 通过npm安装(@syncfusion/ej2-react-calendars)
- CSS主题导入(material3、bootstrap、fluent、tailwind)
- 组件导入与配置
- 基础JSX实现DatePickerComponent
- 函数组件与类组件示例
- 运行第一个应用
Date Formats & Input
日期格式与输入
📄 Read: references/date-formats-and-input.md
- Display format property and patterns (yyyy-MM-dd, dd/MM/yyyy, etc.)
- Custom format specifiers (# and 0 patterns)
- Input formats for flexible date entry (accepting multiple formats)
- Format examples with real-world scenarios
- Parsing and converting user input automatically
- Culture-based default formatting
📄 阅读: references/date-formats-and-input.md
- 显示格式属性与模式(yyyy-MM-dd、dd/MM/yyyy等)
- 自定义格式说明符(#和0模式)
- 灵活日期输入的输入格式(支持多种格式)
- 真实场景的格式示例
- 自动解析与转换用户输入
- 基于文化的默认格式化
Date Range & Validation
日期范围与验证
📄 Read: references/date-range-and-validation.md
- Min and max date properties for range restriction
- Range validation and error states
- strictMode for automatic out-of-range correction
- Out-of-range behavior and error handling
- Disabling dates outside valid range
- Edge cases and gotchas
📄 阅读: references/date-range-and-validation.md
- 最小和最大日期属性限制范围
- 范围验证与错误状态
- strictMode自动修正超出范围的日期
- 超出范围的行为与错误处理
- 禁用有效范围外的日期
- 边缘情况与注意事项
Date Views & Navigation
日期视图与导航
📄 Read: references/date-views-and-navigation.md
- Start property (month, year, decade initial view)
- Depth property for restricting view levels
- Calendar navigation and user interactions
- Month and year selection shortcuts
- Navigating between different views
- Default behavior and best practices
📄 阅读: references/date-views-and-navigation.md
- start属性(月、年、十年初始视图)
- depth属性限制视图层级
- 日历导航与用户交互
- 月份和年份选择快捷方式
- 不同视图间导航
- 默认行为与最佳实践
Customization & Styling
自定义与样式
📄 Read: references/customization-and-styling.md
- CSS classes for styling (e-datepicker, e-calendar, e-day, etc.)
- renderDayCell event for day customization
- Disabling specific dates and weekends
- Placeholder, disabled, and readonly states
- Custom CSS and theme customization
- Day cell appearance and behavior
📄 阅读: references/customization-and-styling.md
- 样式用CSS类(e-datepicker、e-calendar、e-day等)
- renderDayCell事件自定义日期
- 禁用特定日期和周末
- 占位符、禁用和只读状态
- 自定义CSS与主题定制
- 日期单元格外观与行为
Globalization & Localization
全球化与本地化
📄 Read: references/globalization-and-localization.md
- Culture and locale configuration (German, French, Arabic, etc.)
- Loading CLDR data for internationalization
- Date format by culture (different countries, different formats)
- Locale text customization (today button, placeholder)
- Right-to-Left (RTL) support for Arabic, Hebrew, Urdu
- Week start day by culture
- Number formatting and calendar adjustments
📄 阅读: references/globalization-and-localization.md
- 文化与区域配置(德语、法语、阿拉伯语等)
- 加载CLDR数据用于国际化
- 基于文化的日期格式(不同国家不同格式)
- 区域文本自定义(今日按钮、占位符)
- 从右到左(RTL)支持阿拉伯语、希伯来语、乌尔都语
- 基于文化的一周起始日
- 数字格式化与日历调整
Accessibility & Keyboard Navigation
无障碍访问与键盘导航
📄 Read: references/accessibility-and-keyboard.md
- WCAG 2.2 compliance and accessibility standards
- Keyboard navigation shortcuts (Alt+Down, arrow keys, Esc)
- ARIA attributes (aria-expanded, aria-disabled, aria-activedescendant)
- Screen reader support and announcements
- Focus management and visible focus indicators
- Color contrast and visual accessibility
- Mobile device support
📄 阅读: references/accessibility-and-keyboard.md
- WCAG 2.2合规性与无障碍标准
- 键盘导航快捷键(Alt+Down、方向键、Esc)
- ARIA属性(aria-expanded、aria-disabled、aria-activedescendant)
- 屏幕阅读器支持与提示
- 焦点管理与可见焦点指示器
- 颜色对比度与视觉无障碍
- 移动设备支持
Date Masking & Advanced Validation
日期掩码与高级验证
📄 Read: references/date-masking-and-strict-mode.md
- property for structured segment-by-segment date input
enableMask - for custom segment placeholder text
maskPlaceholder - Date masking patterns for input guidance
- property behavior and enforcement
strictMode - Date parsing rules and validation logic
- Input validation and format enforcement
- Edge cases (leap years, month boundaries, etc.)
- Troubleshooting common validation issues
- Best practices for date input
📄 阅读: references/date-masking-and-strict-mode.md
- 属性支持结构化分段日期输入
enableMask - 自定义分段占位文本
maskPlaceholder - 日期掩码模式引导输入
- 属性行为与强制规则
strictMode - 日期解析规则与验证逻辑
- 输入验证与格式强制
- 边缘情况(闰年、月份边界等)
- 常见验证问题排查
- 日期输入最佳实践
Quick Start Example
快速入门示例
Here's a minimal working example to get started:
jsx
import React, { useState } from 'react';
import { DatePickerComponent } from '@syncfusion/ej2-react-calendars';
import '@syncfusion/ej2-base/styles/material3.css';
import '@syncfusion/ej2-buttons/styles/material3.css';
import '@syncfusion/ej2-inputs/styles/material3.css';
import '@syncfusion/ej2-popups/styles/material3.css';
import '@syncfusion/ej2-react-calendars/styles/material3.css';
export default function App() {
const [selectedDate, setSelectedDate] = useState(new Date());
return (
<div style={{ padding: '20px' }}>
<h3>Select a Date</h3>
<DatePickerComponent
value={selectedDate}
change={(e) => setSelectedDate(e.value)}
placeholder="Enter date"
/>
<p>Selected: {selectedDate?.toDateString()}</p>
</div>
);
}Key points:
- Import from
DatePickerComponent@syncfusion/ej2-react-calendars - Import all required CSS themes (base, buttons, inputs, popups, calendars)
- Use prop for the current date (can be null or Date object)
value - Use event (not
change) to update React state — this is the Syncfusion event nameonChange - DatePicker opens a calendar popup on click or Alt+Down arrow
以下是一个极简的可用示例:
jsx
import React, { useState } from 'react';
import { DatePickerComponent } from '@syncfusion/ej2-react-calendars';
import '@syncfusion/ej2-base/styles/material3.css';
import '@syncfusion/ej2-buttons/styles/material3.css';
import '@syncfusion/ej2-inputs/styles/material3.css';
import '@syncfusion/ej2-popups/styles/material3.css';
import '@syncfusion/ej2-react-calendars/styles/material3.css';
export default function App() {
const [selectedDate, setSelectedDate] = useState(new Date());
return (
<div style={{ padding: '20px' }}>
<h3>选择日期</h3>
<DatePickerComponent
value={selectedDate}
change={(e) => setSelectedDate(e.value)}
placeholder="输入日期"
/>
<p>已选择: {selectedDate?.toDateString()}</p>
</div>
);
}关键点:
- 从导入
@syncfusion/ej2-react-calendarsDatePickerComponent - 导入所有必需的CSS主题(base、buttons、inputs、popups、calendars)
- 使用属性设置当前日期(可为null或Date对象)
value - 使用事件(而非
change)更新React状态 — 这是Syncfusion的事件名称onChange - 点击或按Alt+Down箭头可打开DatePicker的日历弹窗
Common Patterns
常见模式
1. Date Range Picker (Min/Max Dates)
1. 日期范围选择器(最小/最大日期)
jsx
<DatePickerComponent
value={new Date()}
min={new Date(2026, 0, 1)}
max={new Date(2026, 11, 31)}
placeholder="Select a date in 2026"
/>jsx
<DatePickerComponent
value={new Date()}
min={new Date(2026, 0, 1)}
max={new Date(2026, 11, 31)}
placeholder="选择2026年的日期"
/>2. Custom Date Format
2. 自定义日期格式
jsx
<DatePickerComponent
value={new Date()}
format="dd/MM/yyyy"
placeholder="DD/MM/YYYY"
/>jsx
<DatePickerComponent
value={new Date()}
format="dd/MM/yyyy"
placeholder="DD/MM/YYYY"
/>3. Multiple Accepted Input Formats
3. 多输入格式支持
jsx
<DatePickerComponent
value={new Date()}
format="yyyy-MM-dd"
inputFormats={['dd/MM/yyyy', 'yyyy-MM-dd', 'yyyyMMdd']}
placeholder="Enter date (dd/MM/yyyy or yyyy-MM-dd)"
/>jsx
<DatePickerComponent
value={new Date()}
format="yyyy-MM-dd"
inputFormats={['dd/MM/yyyy', 'yyyy-MM-dd', 'yyyyMMdd']}
placeholder="输入日期 (dd/MM/yyyy 或 yyyy-MM-dd)"
/>4. Year/Decade View for Birth Date Selection
4. 生日选择的年/十年视图
jsx
<DatePickerComponent
value={new Date()}
start="Decade"
depth="Year"
placeholder="Select year"
/>jsx
<DatePickerComponent
value={new Date()}
start="Decade"
depth="Year"
placeholder="选择年份"
/>5. Disable Weekends
5. 禁用周末
jsx
<DatePickerComponent
value={new Date()}
renderDayCell={(args) => {
if ((args.date.getDay()) === 0 || (args.date.getDay()) === 6) {
args.isDisabled = true;
}
}}
placeholder="Weekdays only"
/>jsx
<DatePickerComponent
value={new Date()}
renderDayCell={(args) => {
if ((args.date.getDay()) === 0 || (args.date.getDay()) === 6) {
args.isDisabled = true;
}
}}
placeholder="仅工作日"
/>6. Controlled Component in React Form
6. React表单中的受控组件
jsx
const [date, setDate] = useState(null);
<DatePickerComponent
value={date}
change={(e) => setDate(e.value)}
format="yyyy-MM-dd"
strictMode={true}
placeholder="Enter date"
/>jsx
const [date, setDate] = useState(null);
<DatePickerComponent
value={date}
change={(e) => setDate(e.value)}
format="yyyy-MM-dd"
strictMode={true}
placeholder="输入日期"
/>7. German Culture with RTL Support
7. 德语文化与RTL支持
jsx
<DatePickerComponent
locale="de"
enableRtl={false}
firstDayOfWeek={1}
value={new Date()}
placeholder="Datum eingeben"
/>jsx
<DatePickerComponent
locale="de"
enableRtl={false}
firstDayOfWeek={1}
value={new Date()}
placeholder="Datum eingeben"
/>8. Masked Date Input
8. 掩码日期输入
jsx
<DatePickerComponent
enableMask={true}
format="MM/dd/yyyy"
maskPlaceholder={{ day: 'DD', month: 'MM', year: 'YYYY' }}
placeholder="Select a date"
/>jsx
<DatePickerComponent
enableMask={true}
format="MM/dd/yyyy"
maskPlaceholder={{ day: 'DD', month: 'MM', year: 'YYYY' }}
placeholder="选择日期"
/>9. Programmatic Control
9. 程序化控制
jsx
import { useRef } from 'react';
const datePickerRef = useRef(null);
// Open calendar
datePickerRef.current.show();
// Close calendar
datePickerRef.current.hide();
// Focus
datePickerRef.current.focusIn();
// Get current view
const view = datePickerRef.current.currentView(); // "Month" | "Year" | "Decade"
// Navigate to specific view
datePickerRef.current.navigateTo('Year', new Date(2026, 0, 1));
<DatePickerComponent ref={datePickerRef} value={new Date()} />jsx
import { useRef } from 'react';
const datePickerRef = useRef(null);
// 打开日历
datePickerRef.current.show();
// 关闭日历
datePickerRef.current.hide();
// 设置焦点
datePickerRef.current.focusIn();
// 获取当前视图
const view = datePickerRef.current.currentView(); // "Month" | "Year" | "Decade"
// 导航到指定视图
datePickerRef.current.navigateTo('Year', new Date(2026, 0, 1));
<DatePickerComponent ref={datePickerRef} value={new Date()} />10. Handle All Key Events
10. 处理所有关键事件
jsx
<DatePickerComponent
value={new Date()}
change={(e) => console.log('Changed:', e.value)}
focus={(e) => console.log('Focused')}
blur={(e) => console.log('Blurred')}
open={(e) => console.log('Opened')}
close={(e) => console.log('Closed')}
cleared={(e) => console.log('Cleared')}
navigated={(e) => console.log('Navigated to view:', e.view)}
renderDayCell={(args) => {
// Disable weekends
if (args.date.getDay() === 0 || args.date.getDay() === 6) {
args.isDisabled = true;
}
}}
/>jsx
<DatePickerComponent
value={new Date()}
change={(e) => console.log('Changed:', e.value)}
focus={(e) => console.log('Focused')}
blur={(e) => console.log('Blurred')}
open={(e) => console.log('Opened')}
close={(e) => console.log('Closed')}
cleared={(e) => console.log('Cleared')}
navigated={(e) => console.log('Navigated to view:', e.view)}
renderDayCell={(args) => {
// 禁用周末
if (args.date.getDay() === 0 || args.date.getDay() === 6) {
args.isDisabled = true;
}
}}
/>DateRangePicker
DateRangePicker组件
The Syncfusion React DateRangePickerComponent enables users to select a start and end date range with built-in support for presets, validation, custom formatting, separator configuration, full-screen mobile mode, and advanced range constraints (minDays, maxDays, min, max).
Syncfusion React DateRangePickerComponent支持用户选择开始和结束日期范围,内置预设选项、验证、自定义格式化、分隔符配置、移动端全屏模式,以及高级范围限制(minDays、maxDays、min、max)。
Documentation Navigation Guide
文档导航指南
Getting Started
快速入门
📄 Read: references/getting-started.md
- Installation via npm (@syncfusion/ej2-react-calendars)
- CSS imports and theme configuration
- Basic DateRangePicker implementation
- Class component vs functional component setup
- Component initialization and structure
- Running development server
- Common troubleshooting
📄 阅读: references/getting-started.md
- 通过npm安装(@syncfusion/ej2-react-calendars)
- CSS导入与主题配置
- 基础DateRangePicker实现
- 类组件与函数组件配置
- 组件初始化与结构
- 运行开发服务器
- 常见故障排除
Date Range Selection
日期范围选择
📄 Read: references/date-range-selection.md
- Start and end date properties
- Date range validation patterns
- Minimum and maximum date constraints
- Disabled dates configuration
- Date range presets (Last 7 days, Last 30 days, etc.)
- Value binding and two-way updates
- Read-only and disabled states
- Placeholder and labels
📄 阅读: references/date-range-selection.md
- 开始和结束日期属性
- 日期范围验证模式
- 最小和最大日期限制
- 禁用日期配置
- 日期范围预设(最近7天、最近30天等)
- 值绑定与双向更新
- 只读和禁用状态
- 占位符与标签
Date Range Formatting
日期范围格式化
📄 Read: references/date-range-formatting.md
- Date format string options (MM/dd/yyyy, dd-MMM-yyyy, etc.)
- Display format vs input format
- Locale-based date formatting
- Custom separator between start and end dates
- Float label types (Never, Always, Auto)
- Placeholder text customization
- htmlAttributes for DOM attributes
📄 阅读: references/date-range-formatting.md
- 日期格式字符串选项(MM/dd/yyyy、dd-MMM-yyyy等)
- 显示格式与输入格式
- 基于区域的日期格式化
- 开始和结束日期间的自定义分隔符
- 浮动标签类型(Never、Always、Auto)
- 占位符文本自定义
- htmlAttributes设置DOM属性
Events and Methods
事件与方法
📄 Read: references/events-and-methods.md
- Event handlers (change, open, close, blur, focus, select)
- Event argument structures
- Methods (show, hide, focusIn, focusOut, reset, destroy)
- Imperative control with useRef
- Lifecycle events (created, destroyed)
- Event patterns and best practices
- Clearing values and state reset
- DateRangeSelectingEvent and ChangedEventArgs
📄 阅读: references/events-and-methods.md
- 事件处理程序(change、open、close、blur、focus、select)
- 事件参数结构
- 方法(show、hide、focusIn、focusOut、reset、destroy)
- 使用useRef进行命令式控制
- 生命周期事件(created、destroyed)
- 事件模式与最佳实践
- 清除值与状态重置
- DateRangeSelectingEvent与ChangedEventArgs
Customization and Styling
自定义与样式
📄 Read: references/customization-and-styling.md
- CSS class customization with cssClass
- Theme options (Material, Bootstrap, Fluent, Tailwind, Fabric)
- Full-screen mode for mobile devices
- RTL (right-to-left) language support
- Preset ranges customization
- Z-index management
- Width and height configuration
- Accessibility features and ARIA attributes
📄 阅读: references/customization-and-styling.md
- 使用cssClass自定义CSS类
- 主题选项(Material、Bootstrap、Fluent、Tailwind、Fabric)
- 移动端全屏模式
- RTL(从右到左)语言支持
- 预设范围自定义
- Z-index管理
- 宽高配置
- 无障碍功能与ARIA属性
API Reference
API参考
📄 Read: references/api-reference.md
- Complete properties list (35+ properties)
- All methods with signatures (8 methods)
- All events with event arguments (12 events)
- Type definitions and interfaces
- Default values and constraints
- Use cases for each property and method
📄 阅读: references/api-reference.md
- 完整属性列表(35+属性)
- 所有方法签名(8个方法)
- 所有事件与事件参数(12个事件)
- 类型定义与接口
- 默认值与限制
- 每个属性和方法的使用场景
Advanced Patterns
高级模式
📄 Read: references/advanced-patterns.md
- Form submission with date range validation
- Keyboard shortcuts and key navigation
- Server timezone offset handling
- Persistence and localStorage
- Multi-component integration (start/end date binding)
- Performance optimization with lazy loading
- Error handling and validation patterns
- Complex date range scenarios (fiscal years, quarters)
📄 阅读: references/advanced-patterns.md
- 带日期范围验证的表单提交
- 键盘快捷键与导航
- 服务器时区偏移处理
- 持久化与localStorage
- 多组件集成(开始/结束日期绑定)
- 懒加载优化性能
- 错误处理与验证模式
- 复杂日期范围场景(财年、季度)
Quick Start
快速入门
tsx
import { DateRangePickerComponent } from '@syncfusion/ej2-react-calendars';
import * as React from 'react';
import '@syncfusion/ej2-base/styles/material3.css';
import '@syncfusion/ej2-buttons/styles/material3.css';
import '@syncfusion/ej2-lists/styles/material3.css';
import '@syncfusion/ej2-inputs/styles/material3.css';
import '@syncfusion/ej2-popups/styles/material3.css';
import '@syncfusion/ej2-calendars/styles/material3.css';
function App() {
const [selectedRange, setSelectedRange] = React.useState<[Date, Date] | null>(null);
const handleDateRangeChange = (e: any) => {
setSelectedRange([e.startDate, e.endDate]);
};
return (
<div style={{ padding: '20px' }}>
<h2>Select Date Range</h2>
<DateRangePickerComponent
id="daterangepicker"
placeholder="Select a range"
change={handleDateRangeChange}
/>
{selectedRange && (
<p>
Selected: {selectedRange[0]?.toLocaleDateString()} - {selectedRange[1]?.toLocaleDateString()}
</p>
)}
</div>
);
}
export default App;tsx
import { DateRangePickerComponent } from '@syncfusion/ej2-react-calendars';
import * as React from 'react';
import '@syncfusion/ej2-base/styles/material3.css';
import '@syncfusion/ej2-buttons/styles/material3.css';
import '@syncfusion/ej2-lists/styles/material3.css';
import '@syncfusion/ej2-inputs/styles/material3.css';
import '@syncfusion/ej2-popups/styles/material3.css';
import '@syncfusion/ej2-calendars/styles/material3.css';
function App() {
const [selectedRange, setSelectedRange] = React.useState<[Date, Date] | null>(null);
const handleDateRangeChange = (e: any) => {
setSelectedRange([e.startDate, e.endDate]);
};
return (
<div style={{ padding: '20px' }}>
<h2>选择日期范围</h2>
<DateRangePickerComponent
id="daterangepicker"
placeholder="选择范围"
change={handleDateRangeChange}
/>
{selectedRange && (
<p>
已选择: {selectedRange[0]?.toLocaleDateString()} - {selectedRange[1]?.toLocaleDateString()}
</p>
)}
</div>
);
}
export default App;Common Patterns
常见模式
Pattern 1: Date Range with Preset Options
模式1:带预设选项的日期范围
tsx
import { DateRangePickerComponent } from '@syncfusion/ej2-react-calendars';
import * as React from 'react';
function ReportingDashboard() {
const [dateRange, setDateRange] = React.useState<[Date, Date] | null>(null);
const getDateRangePresets = () => {
const today = new Date();
const yesterday = new Date(today);
yesterday.setDate(today.getDate() - 1);
const last7Days = new Date(today);
last7Days.setDate(today.getDate() - 7);
const last30Days = new Date(today);
last30Days.setDate(today.getDate() - 30);
const thisMonth = new Date(today.getFullYear(), today.getMonth(), 1);
const lastMonth = new Date(today.getFullYear(), today.getMonth(), 0);
return [
{ text: 'Today', value: [today, today] },
{ text: 'Yesterday', value: [yesterday, yesterday] },
{ text: 'Last 7 Days', value: [last7Days, today] },
{ text: 'Last 30 Days', value: [last30Days, today] },
{ text: 'This Month', value: [thisMonth, today] },
{ text: 'Last Month', value: [new Date(today.getFullYear(), today.getMonth() - 1, 1), lastMonth] },
];
};
const handlePresetClick = (start: Date, end: Date) => {
setDateRange([start, end]);
};
return (
<div style={{ padding: '20px' }}>
<h3>Analytics Report</h3>
<DateRangePickerComponent
id="daterangepicker"
placeholder="Select report date range"
startDate={dateRange?.[0]}
endDate={dateRange?.[1]}
change={(e: any) => setDateRange([e.startDate, e.endDate])}
/>
<div style={{ marginTop: '15px' }}>
{getDateRangePresets().map((preset) => (
<button
key={preset.text}
onClick={() => handlePresetClick(preset.value[0], preset.value[1])}
style={{ marginRight: '10px', padding: '5px 10px' }}
>
{preset.text}
</button>
))}
</div>
</div>
);
}
export default ReportingDashboard;tsx
import { DateRangePickerComponent } from '@syncfusion/ej2-react-calendars';
import * as React from 'react';
function ReportingDashboard() {
const [dateRange, setDateRange] = React.useState<[Date, Date] | null>(null);
const getDateRangePresets = () => {
const today = new Date();
const yesterday = new Date(today);
yesterday.setDate(today.getDate() - 1);
const last7Days = new Date(today);
last7Days.setDate(today.getDate() - 7);
const last30Days = new Date(today);
last30Days.setDate(today.getDate() - 30);
const thisMonth = new Date(today.getFullYear(), today.getMonth(), 1);
const lastMonth = new Date(today.getFullYear(), today.getMonth(), 0);
return [
{ text: '今日', value: [today, today] },
{ text: '昨日', value: [yesterday, yesterday] },
{ text: '最近7天', value: [last7Days, today] },
{ text: '最近30天', value: [last30Days, today] },
{ text: '本月', value: [thisMonth, today] },
{ text: '上月', value: [new Date(today.getFullYear(), today.getMonth() - 1, 1), lastMonth] },
];
};
const handlePresetClick = (start: Date, end: Date) => {
setDateRange([start, end]);
};
return (
<div style={{ padding: '20px' }}>
<h3>分析报告</h3>
<DateRangePickerComponent
id="daterangepicker"
placeholder="选择报告日期范围"
startDate={dateRange?.[0]}
endDate={dateRange?.[1]}
change={(e: any) => setDateRange([e.startDate, e.endDate])}
/>
<div style={{ marginTop: '15px' }}>
{getDateRangePresets().map((preset) => (
<button
key={preset.text}
onClick={() => handlePresetClick(preset.value[0], preset.value[1])}
style={{ marginRight: '10px', padding: '5px 10px' }}
>
{preset.text}
</button>
))}
</div>
</div>
);
}
export default ReportingDashboard;Pattern 2: Date Range with Validation
模式2:带验证的日期范围
tsx
import { DateRangePickerComponent } from '@syncfusion/ej2-react-calendars';
import { ButtonComponent } from '@syncfusion/ej2-react-buttons';
import * as React from 'react';
function BookingForm() {
const [dateRange, setDateRange] = React.useState<[Date, Date] | null>(null);
const [validationError, setValidationError] = React.useState<string>('');
const minDate = new Date();
const maxDate = new Date();
maxDate.setDate(maxDate.getDate() + 90); // 90 days from now
const handleDateRangeChange = (e: any) => {
setValidationError('');
if (!e.startDate || !e.endDate) {
return;
}
const start = new Date(e.startDate);
const end = new Date(e.endDate);
// Validation checks
if (start > end) {
setValidationError('Start date must be before end date');
return;
}
const daysDifference = (end.getTime() - start.getTime()) / (1000 * 60 * 60 * 24);
if (daysDifference > 30) {
setValidationError('Date range cannot exceed 30 days');
return;
}
setDateRange([start, end]);
};
const handleSubmit = (e: React.FormEvent) => {
e.preventDefault();
if (dateRange && !validationError) {
console.log('Booking dates:', {
checkIn: dateRange[0].toLocaleDateString(),
checkOut: dateRange[1].toLocaleDateString(),
});
}
};
return (
<form onSubmit={handleSubmit} style={{ padding: '20px', maxWidth: '500px' }}>
<h3>Book Your Stay</h3>
<label style={{ display: 'block', marginBottom: '8px' }}>
Select Check-in and Check-out Dates (Max 30 days)
</label>
<DateRangePickerComponent
id="daterangepicker"
placeholder="Select check-in and check-out"
min={minDate}
max={maxDate}
startDate={dateRange?.[0]}
endDate={dateRange?.[1]}
change={handleDateRangeChange}
style={{ width: '100%', marginBottom: '8px' }}
/>
{validationError && (
<div style={{ color: 'red', marginBottom: '10px', fontSize: '14px' }}>
⚠️ {validationError}
</div>
)}
<ButtonComponent
type="submit"
isPrimary={true}
disabled={!dateRange || !!validationError}
>
Book Now
</ButtonComponent>
</form>
);
}
export default BookingForm;tsx
import { DateRangePickerComponent } from '@syncfusion/ej2-react-calendars';
import { ButtonComponent } from '@syncfusion/ej2-react-buttons';
import * as React from 'react';
function BookingForm() {
const [dateRange, setDateRange] = React.useState<[Date, Date] | null>(null);
const [validationError, setValidationError] = React.useState<string>('');
const minDate = new Date();
const maxDate = new Date();
maxDate.setDate(maxDate.getDate() + 90); // 从今天起90天内
const handleDateRangeChange = (e: any) => {
setValidationError('');
if (!e.startDate || !e.endDate) {
return;
}
const start = new Date(e.startDate);
const end = new Date(e.endDate);
// 验证检查
if (start > end) {
setValidationError('开始日期必须早于结束日期');
return;
}
const daysDifference = (end.getTime() - start.getTime()) / (1000 * 60 * 60 * 24);
if (daysDifference > 30) {
setValidationError('日期范围不能超过30天');
return;
}
setDateRange([start, end]);
};
const handleSubmit = (e: React.FormEvent) => {
e.preventDefault();
if (dateRange && !validationError) {
console.log('预订日期:', {
checkIn: dateRange[0].toLocaleDateString(),
checkOut: dateRange[1].toLocaleDateString(),
});
}
};
return (
<form onSubmit={handleSubmit} style={{ padding: '20px', maxWidth: '500px' }}>
<h3>预订住宿</h3>
<label style={{ display: 'block', marginBottom: '8px' }}>
选择入住和退房日期(最多30天)
</label>
<DateRangePickerComponent
id="daterangepicker"
placeholder="选择入住和退房日期"
min={minDate}
max={maxDate}
startDate={dateRange?.[0]}
endDate={dateRange?.[1]}
change={handleDateRangeChange}
style={{ width: '100%', marginBottom: '8px' }}
/>
{validationError && (
<div style={{ color: 'red', marginBottom: '10px', fontSize: '14px' }}>
⚠️ {validationError}
</div>
)}
<ButtonComponent
type="submit"
isPrimary={true}
disabled={!dateRange || !!validationError}
>
立即预订
</ButtonComponent>
</form>
);
}
export default BookingForm;Pattern 4: Event Handling and State Management
模式4:事件处理与状态管理
tsx
import { DateRangePickerComponent } from '@syncfusion/ej2-react-calendars';
import * as React from 'react';
function EventTrackingExample() {
const [dateRange, setDateRange] = React.useState<[Date, Date] | null>(null);
const [eventLog, setEventLog] = React.useState<string[]>([]);
const handleSelect = (e: any) => {
setEventLog(prev => [
...prev,
`Selected: ${e.startDate?.toLocaleDateString()} to ${e.endDate?.toLocaleDateString()}`
]);
};
const handleChange = (e: any) => {
setDateRange([e.startDate, e.endDate]);
setEventLog(prev => [...prev, `Changed: ${new Date().toLocaleTimeString()}`]);
};
const handleOpen = (e: any) => {
setEventLog(prev => [...prev, `Popup opened at ${new Date().toLocaleTimeString()}`]);
};
const handleClose = (e: any) => {
setEventLog(prev => [...prev, `Popup closed at ${new Date().toLocaleTimeString()}`]);
};
const clearLog = () => {
setEventLog([]);
};
return (
<div style={{ padding: '20px', display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '20px' }}>
<div>
<h3>DateRangePicker</h3>
<DateRangePickerComponent
id="daterangepicker"
placeholder="Select date range"
select={handleSelect}
change={handleChange}
open={handleOpen}
close={handleClose}
/>
</div>
<div style={{ padding: '10px', border: '1px solid #ccc', borderRadius: '4px' }}>
<h3>Event Log</h3>
<button
onClick={clearLog}
style={{
padding: '5px 10px',
marginBottom: '10px',
backgroundColor: '#f0f0f0',
border: '1px solid #ccc',
cursor: 'pointer'
}}
>
Clear Log
</button>
<ul style={{ maxHeight: '300px', overflowY: 'auto', margin: 0, paddingLeft: '20px' }}>
{eventLog.map((event, idx) => (
<li key={idx} style={{ marginBottom: '5px', fontSize: '12px' }}>
{event}
</li>
))}
</ul>
</div>
</div>
);
}
export default EventTrackingExample;tsx
import { DateRangePickerComponent } from '@syncfusion/ej2-react-calendars';
import * as React from 'react';
function EventTrackingExample() {
const [dateRange, setDateRange] = React.useState<[Date, Date] | null>(null);
const [eventLog, setEventLog] = React.useState<string[]>([]);
const handleSelect = (e: any) => {
setEventLog(prev => [
...prev,
`已选择: ${e.startDate?.toLocaleDateString()} 至 ${e.endDate?.toLocaleDateString()}`
]);
};
const handleChange = (e: any) => {
setDateRange([e.startDate, e.endDate]);
setEventLog(prev => [...prev, `已更改: ${new Date().toLocaleTimeString()}`]);
};
const handleOpen = (e: any) => {
setEventLog(prev => [...prev, `弹窗已打开:${new Date().toLocaleTimeString()}`]);
};
const handleClose = (e: any) => {
setEventLog(prev => [...prev, `弹窗已关闭:${new Date().toLocaleTimeString()}`]);
};
const clearLog = () => {
setEventLog([]);
};
return (
<div style={{ padding: '20px', display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '20px' }}>
<div>
<h3>DateRangePicker</h3>
<DateRangePickerComponent
id="daterangepicker"
placeholder="选择日期范围"
select={handleSelect}
change={handleChange}
open={handleOpen}
close={handleClose}
/>
</div>
<div style={{ padding: '10px', border: '1px solid #ccc', borderRadius: '4px' }}>
<h3>事件日志</h3>
<button
onClick={clearLog}
style={{
padding: '5px 10px',
marginBottom: '10px',
backgroundColor: '#f0f0f0',
border: '1px solid #ccc',
cursor: 'pointer'
}}
>
清除日志
</button>
<ul style={{ maxHeight: '300px', overflowY: 'auto', margin: 0, paddingLeft: '20px' }}>
{eventLog.map((event, idx) => (
<li key={idx} style={{ marginBottom: '5px', fontSize: '12px' }}>
{event}
</li>
))}
</ul>
</div>
</div>
);
}
export default EventTrackingExample;Pattern 5: Custom Date Range Format
模式5:自定义日期范围格式
tsx
import { DateRangePickerComponent } from '@syncfusion/ej2-react-calendars';
import * as React from 'react';
function DateFormatDemo() {
const [formatType, setFormatType] = React.useState<'short' | 'long' | 'custom'>('short');
const [dateRange, setDateRange] = React.useState<[Date, Date] | null>(null);
const getFormat = () => {
switch (formatType) {
case 'short':
return 'M/d/yyyy';
case 'long':
return 'MMMM d, yyyy';
case 'custom':
return 'dd-MMM-yy';
default:
return 'M/d/yyyy';
}
};
return (
<div style={{ padding: '20px' }}>
<h3>Date Range Format Options</h3>
<div style={{ marginBottom: '15px' }}>
<label style={{ marginRight: '10px' }}>Format Type:</label>
{(['short', 'long', 'custom'] as const).map((format) => (
<label key={format} style={{ marginRight: '15px' }}>
<input
type="radio"
name="format"
value={format}
checked={formatType === format}
onChange={(e) => setFormatType(e.target.value as any)}
/>
{format.charAt(0).toUpperCase() + format.slice(1)}
</label>
))}
</div>
<div style={{ marginBottom: '10px', padding: '10px', backgroundColor: '#f5f5f5' }}>
<strong>Format String:</strong> {getFormat()}
</div>
<DateRangePickerComponent
id="daterangepicker"
placeholder="Select date range"
format={getFormat()}
startDate={dateRange?.[0]}
endDate={dateRange?.[1]}
change={(e: any) => setDateRange([e.startDate, e.endDate])}
/>
{dateRange && (
<div style={{ marginTop: '15px', padding: '10px', backgroundColor: '#e8f5e9' }}>
<p>
<strong>Formatted Output:</strong> {dateRange[0].toLocaleDateString('en-US')} - {dateRange[1].toLocaleDateString('en-US')}
</p>
</div>
)}
</div>
);
}
export default DateFormatDemo;tsx
import { DateRangePickerComponent } from '@syncfusion/ej2-react-calendars';
import * as React from 'react';
function DateFormatDemo() {
const [formatType, setFormatType] = React.useState<'short' | 'long' | 'custom'>('short');
const [dateRange, setDateRange] = React.useState<[Date, Date] | null>(null);
const getFormat = () => {
switch (formatType) {
case 'short':
return 'M/d/yyyy';
case 'long':
return 'MMMM d, yyyy';
case 'custom':
return 'dd-MMM-yy';
default:
return 'M/d/yyyy';
}
};
return (
<div style={{ padding: '20px' }}>
<h3>日期范围格式选项</h3>
<div style={{ marginBottom: '15px' }}>
<label style={{ marginRight: '10px' }}>格式类型:</label>
{(['short', 'long', 'custom'] as const).map((format) => (
<label key={format} style={{ marginRight: '15px' }}>
<input
type="radio"
name="format"
value={format}
checked={formatType === format}
onChange={(e) => setFormatType(e.target.value as any)}
/>
{format.charAt(0).toUpperCase() + format.slice(1)}
</label>
))}
</div>
<div style={{ marginBottom: '10px', padding: '10px', backgroundColor: '#f5f5f5' }}>
<strong>格式字符串:</strong> {getFormat()}
</div>
<DateRangePickerComponent
id="daterangepicker"
placeholder="选择日期范围"
format={getFormat()}
startDate={dateRange?.[0]}
endDate={dateRange?.[1]}
change={(e: any) => setDateRange([e.startDate, e.endDate])}
/>
{dateRange && (
<div style={{ marginTop: '15px', padding: '10px', backgroundColor: '#e8f5e9' }}>
<p>
<strong>格式化输出:</strong> {dateRange[0].toLocaleDateString('en-US')} - {dateRange[1].toLocaleDateString('en-US')}
</p>
</div>
)}
</div>
);
}
export default DateFormatDemo;Key Props Reference
关键属性参考
- Prop: : Type:
startDate— Default:Date— Initial start date of the range.null - Prop: : Type:
endDate— Default:Date— Initial end date of the range.null - Prop: : Type:
min— Default:Date— Minimum selectable date.new Date(1900, 0, 1) - Prop: : Type:
max— Default:Date— Maximum selectable date.new Date(2099, 11, 31) - Prop: : Type:
value— Default:Date[] | DateRange— Gets or sets the start and end date.null - Prop: : Type:
format— Default:string | RangeFormatObject— Date display and input format.null - Prop: : Type:
placeholder— Default:string— Input placeholder text.null - Prop: : Type:
enabled— Default:boolean— Enables or disables the component (usetrue, notenabled).disabled - Prop: : Type:
readonly— Default:boolean— Read-only state; prevents editing.false - Prop: : Type:
allowEdit— Default:boolean— Allow manual text editing of the input.true - Prop: : Type:
cssClass— Default:string— Adds a custom CSS class to the root element.'' - Prop: : Type:
floatLabelType— Default:FloatLabelType | string— Float label behavior (Never, Always, Auto).Never - Prop: : Type:
separator— Default:string— Separator string between start and end date in the input.'-' - Prop: : Type:
locale— Default:string— Locale used for formatting and localization.'en-US' - Prop: : Type:
inputFormats— Default:string[] | RangeFormatObject[]— Acceptable input parsing formats.null - Prop: : Type:
keyConfigs— Default:object— Custom keyboard shortcuts mapping.null - Prop: : Type:
firstDayOfWeek— Default:number— First day of week for calendar rendering.null - Prop: : Type:
dayHeaderFormat— Default:DayHeaderFormats— Day name format in header.Short - Prop: : Type:
start— Default:CalendarView— Initial calendar view when popup opens.Month - Prop: : Type:
depth— Default:CalendarView— Maximum navigation depth for the calendar.Month - Prop: : Type:
weekNumber— Default:boolean— Show week numbers in calendar rows.false - Prop: : Type:
weekRule— Default:WeekRule— Rule that defines first week of the year.FirstDay - Prop: : Type:
minDays— Default:number— Minimum allowed span of days in a selection.null - Prop: : Type:
maxDays— Default:number— Maximum allowed span of days in a selection.null - Prop: : Type:
strictMode— Default:boolean— When true, only valid ranges can be entered.false - Prop: : Type:
showClearButton— Default:boolean— Toggle visibility of the clear button.true - Prop: : Type:
fullScreenMode— Default:boolean— Use full-screen popup on mobile.false - Prop: : Type:
htmlAttributes— Default:{ [key: string]: string }— Additional HTML attributes applied to the component element.{} - Prop: : Type:
serverTimezoneOffset— Default:number— Server timezone offset in minutes for initial value processing.null - Prop: : Type:
width— Default:number | string— Width of the component input.'' - Prop: : Type:
zIndex— Default:number— z-index for popup element.1000
Next Steps:
- Read references/getting-started.md to install and set up your first DateRangePicker
- Explore references/date-range-selection.md for range selection patterns
- Check references/date-range-formatting.md for format options
- See references/advanced-patterns.md for complex scenarios
- Refer to references/api-reference.md for complete API documentation
- 属性: : 类型:
startDate— 默认值:Date— 范围的初始开始日期。null - 属性: : 类型:
endDate— 默认值:Date— 范围的初始结束日期。null - 属性: : 类型:
min— 默认值:Date— 可选的最小日期。new Date(1900, 0, 1) - 属性: : 类型:
max— 默认值:Date— 可选的最大日期。new Date(2099, 11, 31) - 属性: : 类型:
value— 默认值:Date[] | DateRange— 获取或设置开始和结束日期。null - 属性: : 类型:
format— 默认值:string | RangeFormatObject— 日期显示和输入格式。null - 属性: : 类型:
placeholder— 默认值:string— 输入框占位文本。null - 属性: : 类型:
enabled— 默认值:boolean— 启用或禁用组件(使用true,而非enabled)。disabled - 属性: : 类型:
readonly— 默认值:boolean— 只读状态;禁止编辑。false - 属性: : 类型:
allowEdit— 默认值:boolean— 允许手动编辑输入框文本。true - 属性: : 类型:
cssClass— 默认值:string— 为根元素添加自定义CSS类。'' - 属性: : 类型:
floatLabelType— 默认值:FloatLabelType | string— 浮动标签行为(Never、Always、Auto)。Never - 属性: : 类型:
separator— 默认值:string— 输入框中开始和结束日期之间的分隔符。'-' - 属性: : 类型:
locale— 默认值:string— 用于格式化和本地化的区域设置。'en-US' - 属性: : 类型:
inputFormats— 默认值:string[] | RangeFormatObject[]— 可接受的输入解析格式。null - 属性: : 类型:
keyConfigs— 默认值:object— 自定义键盘快捷键映射。null - 属性: : 类型:
firstDayOfWeek— 默认值:number— 日历渲染的一周第一天。null - 属性: : 类型:
dayHeaderFormat— 默认值:DayHeaderFormats— 表头中的日期名称格式。Short - 属性: : 类型:
start— 默认值:CalendarView— 弹窗打开时的初始日历视图。Month - 属性: : 类型:
depth— 默认值:CalendarView— 日历的最大导航深度。Month - 属性: : 类型:
weekNumber— 默认值:boolean— 在日历行中显示周数。false - 属性: : 类型:
weekRule— 默认值:WeekRule— 定义一年第一周的规则。FirstDay - 属性: : 类型:
minDays— 默认值:number— 选择的最小天数跨度。null - 属性: : 类型:
maxDays— 默认值:number— 选择的最大天数跨度。null - 属性: : 类型:
strictMode— 默认值:boolean— 为true时,仅允许输入有效范围。false - 属性: : 类型:
showClearButton— 默认值:boolean— 切换清除按钮的可见性。true - 属性: : 类型:
fullScreenMode— 默认值:boolean— 在移动端使用全屏弹窗。false - 属性: : 类型:
htmlAttributes— 默认值:{ [key: string]: string }— 应用于组件元素的额外HTML属性。{} - 属性: : 类型:
serverTimezoneOffset— 默认值:number— 初始值处理的服务器时区偏移量(分钟)。null - 属性: : 类型:
width— 默认值:number | string— 组件输入框的宽度。'' - 属性: : 类型:
zIndex— 默认值:number— 弹窗元素的层级。1000
下一步:
- 阅读references/getting-started.md安装并设置你的第一个DateRangePicker
- 探索references/date-range-selection.md了解范围选择模式
- 查看references/date-range-formatting.md了解格式选项
- 查看references/advanced-patterns.md了解复杂场景
- 参考references/api-reference.md获取完整API文档
DateTimePicker
DateTimePicker组件
The Syncfusion React DateTimePickerComponent combines date and time selection in a single control. It offers calendar + time list popup, customizable time steps, masking, strict validation, timezone handling, format customization, and full keyboard accessibility.
Syncfusion React DateTimePickerComponent在单个控件中结合了日期和时间选择功能。它提供日历+时间列表弹窗、可自定义的时间步长、掩码、严格验证、时区处理、格式自定义,以及完整的键盘无障碍支持。
Documentation (read these references in order)
文档(按顺序阅读这些参考)
- 📄 Read: references/getting-started.md — installation, module setup, CSS imports, basic usage
- 📄 Read: references/api-reference.md — full properties, methods, and events
- 📄 Read: references/date-time-selection.md — selection patterns and constraints
- 📄 Read: references/time-configuration.md — step, minTime/maxTime, scroll behavior
- 📄 Read: references/events-and-methods.md — event handlers and method usage
- 📄 Read: references/styling-and-customization.md — themes and cssClass usage
- 📄 Read: references/advanced-features.md — masked input, strict mode, calendar modes, timezone handling
- 📄 Read: references/accessibility.md — keyboard and ARIA guidance
- 📄 阅读: references/getting-started.md — 安装、模块配置、CSS导入、基础用法
- 📄 阅读: references/api-reference.md — 完整属性、方法和事件
- 📄 阅读: references/date-time-selection.md — 选择模式和限制
- 📄 阅读: references/time-configuration.md — 步长、minTime/maxTime、滚动行为
- 📄 阅读: references/events-and-methods.md — 事件处理程序和方法用法
- 📄 阅读: references/styling-and-customization.md — 主题和cssClass用法
- 📄 阅读: references/advanced-features.md — 掩码输入、严格模式、日历模式、时区处理
- 📄 阅读: references/accessibility.md — 键盘和ARIA指南
Quick Start (React + TypeScript)
React + TypeScript快速入门
- Install package:
bash
npm install @syncfusion/ej2-react-calendars- Import styles (in or component CSS):
index.css
css
@import '../node_modules/@syncfusion/ej2-base/styles/material3.css';
@import '../node_modules/@syncfusion/ej2-calendars/styles/material3.css';- Minimal functional example ():
App.tsx
tsx
import React, { useState } from 'react';
import { DateTimePickerComponent } from '@syncfusion/ej2-react-calendars';
export default function App() {
const [value, setValue] = useState<Date | null>(new Date());
return (
<div style={{ padding: 20 }}>
<h3>Choose date and time</h3>
<DateTimePickerComponent
value={value}
change={(e) => setValue((e as any).value)}
format="dd/MM/yyyy hh:mm a"
step={15}
placeholder="Select date and time"
/>
<p>Selected: {value ? value.toString() : 'none'}</p>
</div>
);
}- 安装包:
bash
npm install @syncfusion/ej2-react-calendars- 导入样式(在或组件CSS中):
index.css
css
@import '../node_modules/@syncfusion/ej2-base/styles/material3.css';
@import '../node_modules/@syncfusion/ej2-calendars/styles/material3.css';- 极简函数示例():
App.tsx
tsx
import React, { useState } from 'react';
import { DateTimePickerComponent } from '@syncfusion/ej2-react-calendars';
export default function App() {
const [value, setValue] = useState<Date | null>(new Date());
return (
<div style={{ padding: 20 }}>
<h3>选择日期和时间</h3>
<DateTimePickerComponent
value={value}
change={(e) => setValue((e as any).value)}
format="dd/MM/yyyy hh:mm a"
step={15}
placeholder="选择日期和时间"
/>
<p>已选择: {value ? value.toString() : '无'}</p>
</div>
);
}Common Patterns
常见模式
- Controlled value: bind and update on
value.change - Range enforcement: use and
minfor dates,max/minTimefor times.maxTime - Masked input: enable with and provide
enableMask.maskPlaceholder - Localization: set or use global culture settings.
locale - Keyboard-first: provide for custom shortcuts.
keyConfigs
- 受控值: 绑定并在
value事件中更新。change - 范围强制: 使用和
min限制日期,max/minTime限制时间。maxTime - 掩码输入: 使用启用并设置
enableMask。maskPlaceholder - 本地化: 设置或使用全局文化设置。
locale - 优先键盘操作: 提供自定义快捷键。
keyConfigs
Key Props Summary (see API reference for full list)
关键属性摘要(完整列表请参阅API参考)
- ,
value,min,max,step,format,enableMask,placeholder,cssClass,locale,readonly.enabled
- ,
value,min,max,step,format,enableMask,placeholder,cssClass,locale,readonly.enabled
Key Events
关键事件
- ,
change,open,close,created,destroyed,navigated,blur,focus.renderDayCell
- ,
change,open,close,created,destroyed,navigated,blur,focus.renderDayCell
Next steps
下一步
- All reference files have been created and validated against the official Syncfusion API (see ).
references/api-reference.md - Next: run the test-case guide and validation checks, then create automated examples or add platform-specific notes on request.
- Ask me to run tests, update , or produce publish-ready artifacts.
completion-status.json
- 所有参考文件已创建并通过官方Syncfusion API验证(请参阅)。
references/api-reference.md - 下一步: 运行测试用例指南和验证检查,然后根据需求创建自动化示例或添加平台特定说明。
- 可要求我运行测试、更新或生成可发布的成品。
completion-status.json
TimePicker
TimePicker组件
The Syncfusion React TimePickerComponent is a lightweight and feature-rich control for selecting time values. It supports 12/24-hour formats, time stepping, min/max constraints, masked input, localization, full-screen mode, and easy integration into React forms.
Syncfusion React TimePickerComponent是一个轻量且功能丰富的控件,用于选择时间值。它支持12/24小时格式、时间步长、最小/最大限制、掩码输入、本地化、全屏模式,并可轻松集成到React表单中。
Documentation Navigation Guide
文档导航指南
Getting Started
快速入门
📄 Read: references/getting-started.md
- Installation via npm (@syncfusion/ej2-react-calendars)
- CalendarModule setup in app.module.ts
- CSS imports and theme configuration
- Basic TimePicker implementation
- Component registration with useRef
- Running development server
- Common troubleshooting
📄 阅读: references/getting-started.md
- 通过npm安装(@syncfusion/ej2-react-calendars)
- 在app.module.ts中配置CalendarModule
- CSS导入与主题配置
- 基础TimePicker实现
- 使用useRef注册组件
- 运行开发服务器
- 常见故障排除
Time Format and Display
时间格式与显示
📄 Read: references/time-format-and-display.md
- Format string options (24-hour, 12-hour formats)
- TimeFormatObject with skeleton property
- Locale-based time formatting
- Placeholder text customization
- Float label types (Never, Always, Auto)
- htmlAttributes for DOM attributes
- Masked input with enableMask
- Mask placeholder configuration
📄 阅读: references/time-format-and-display.md
- 格式字符串选项(24小时、12小时格式)
- 带skeleton属性的TimeFormatObject
- 基于区域的时间格式化
- 占位符文本自定义
- 浮动标签类型(Never、Always、Auto)
- htmlAttributes设置DOM属性
- 启用enableMask的掩码输入
- 掩码占位符配置
Time Range and Selection
时间范围与选择
📄 Read: references/time-range-and-selection.md
- Minimum and maximum time constraints
- Time step intervals (15, 30, 60 minutes)
- ScrollTo default position
- Value binding and two-way updates
- Read-only and disabled states
- OpenOnFocus behavior
- Time popup list population
- Stepped time intervals
📄 阅读: references/time-range-and-selection.md
- 最小和最大时间限制
- 时间步长间隔(15、30、60分钟)
- ScrollTo默认位置
- 值绑定与双向更新
- 只读和禁用状态
- OpenOnFocus行为
- 时间弹窗列表生成
- 步进时间间隔
Events and Methods
事件与方法
📄 Read: references/events-and-methods.md
- Event handlers (change, open, close, blur, focus)
- Event argument structures
- Methods (show, hide, focusIn, focusOut)
- Imperative control with useRef
- Lifecycle events (created, destroyed)
- Event patterns and best practices
- Clearing values and state reset
- ItemRender for custom formatting
📄 阅读: references/events-and-methods.md
- 事件处理程序(change、open、close、blur、focus)
- 事件参数结构
- 方法(show、hide、focusIn、focusOut)
- 使用useRef进行命令式控制
- 生命周期事件(created、destroyed)
- 事件模式与最佳实践
- 清除值与状态重置
- ItemRender自定义格式化
Customization and Styling
自定义与样式
📄 Read: references/customization-and-styling.md
- CSS class customization with cssClass
- Theme options (Material, Bootstrap, Fluent, Tailwind)
- Full-screen mode for mobile devices
- RTL (right-to-left) language support
- Strict mode validation
- Z-index management
- Width and height configuration
- Accessibility features
- Theme Studio integration
📄 阅读: references/customization-and-styling.md
- 使用cssClass自定义CSS类
- 主题选项(Material、Bootstrap、Fluent、Tailwind)
- 移动端全屏模式
- RTL(从右到左)语言支持
- 严格模式验证
- Z-index管理
- 宽高配置
- 无障碍功能
- Theme Studio集成
API Reference
API参考
📄 Read: references/api-reference.md
- Complete properties list (26 properties)
- All methods with signatures (5 methods)
- All events with event arguments (9 events)
- Type definitions and interfaces
- Default values and constraints
- Use cases for each property
📄 阅读: references/api-reference.md
- 完整属性列表(26个属性)
- 所有方法签名(5个方法)
- 所有事件与事件参数(9个事件)
- 类型定义与接口
- 默认值与限制
- 每个属性的使用场景
Advanced Patterns
高级模式
📄 Read: references/advanced-patterns.md
- Form submission with validation
- Keyboard shortcuts and keyConfigs
- Server timezone offset handling
- Persistence and localStorage
- Multi-component integration
- Performance optimization
- Error handling patterns
- Complex validation scenarios
📄 阅读: references/advanced-patterns.md
- 带验证的表单提交
- 键盘快捷键与keyConfigs
- 服务器时区偏移处理
- 持久化与localStorage
- 多组件集成
- 性能优化
- 错误处理模式
- 复杂验证场景
Quick Start
快速入门
tsx
import { TimePickerComponent } from '@syncfusion/ej2-react-calendars';
import * as React from 'react';
import '@syncfusion/ej2-base/styles/material3.css';
import '@syncfusion/ej2-calendars/styles/material3.css';
function App() {
const [selectedTime, setSelectedTime] = React.useState(new Date('1/1/2018 9:00 AM'));
const handleChange = (e: any) => {
setSelectedTime(e.value);
};
return (
<div style={{ padding: '20px' }}>
<h2>Select Time</h2>
<TimePickerComponent
value={selectedTime}
change={handleChange}
placeholder="Select a time"
/>
<p>Selected: {selectedTime ? selectedTime.toLocaleTimeString() : 'None'}</p>
</div>
);
}
export default App;tsx
import { TimePickerComponent } from '@syncfusion/ej2-react-calendars';
import * as React from 'react';
import '@syncfusion/ej2-base/styles/material3.css';
import '@syncfusion/ej2-calendars/styles/material3.css';
function App() {
const [selectedTime, setSelectedTime] = React.useState(new Date('1/1/2018 9:00 AM'));
const handleChange = (e: any) => {
setSelectedTime(e.value);
};
return (
<div style={{ padding: '20px' }}>
<h2>选择时间</h2>
<TimePickerComponent
value={selectedTime}
change={handleChange}
placeholder="选择时间"
/>
<p>已选择: {selectedTime ? selectedTime.toLocaleTimeString() : '无'}</p>
</div>
);
}
export default App;Common Patterns
常见模式
Pattern 1: Time Picker with Min/Max Constraints
模式1:带最小/最大限制的时间选择器
tsx
import { TimePickerComponent } from '@syncfusion/ej2-react-calendars';
import * as React from 'react';
function AppointmentScheduler() {
const [appointmentTime, setAppointmentTime] = React.useState(new Date('1/1/2018 9:00 AM'));
const minTime = new Date('1/1/2018 8:00 AM');
const maxTime = new Date('1/1/2018 5:00 PM');
return (
<div>
<h3>Select Appointment Time (8 AM - 5 PM)</h3>
<TimePickerComponent
value={appointmentTime}
min={minTime}
max={maxTime}
step={30}
change={(e: any) => setAppointmentTime(e.value)}
placeholder="Choose time"
/>
</div>
);
}
export default AppointmentScheduler;tsx
import { TimePickerComponent } from '@syncfusion/ej2-react-calendars';
import * as React from 'react';
function AppointmentScheduler() {
const [appointmentTime, setAppointmentTime] = React.useState(new Date('1/1/2018 9:00 AM'));
const minTime = new Date('1/1/2018 8:00 AM');
const maxTime = new Date('1/1/2018 5:00 PM');
return (
<div>
<h3>选择预约时间(上午8点 - 下午5点)</h3>
<TimePickerComponent
value={appointmentTime}
min={minTime}
max={maxTime}
step={30}
change={(e: any) => setAppointmentTime(e.value)}
placeholder="选择时间"
/>
</div>
);
}
export default AppointmentScheduler;Pattern 2: Form with Time Picker Submission
模式2:带时间选择器的表单提交
tsx
import { TimePickerComponent } from '@syncfusion/ej2-react-calendars';
import { ButtonComponent } from '@syncfusion/ej2-react-buttons';
import * as React from 'react';
function ScheduleForm() {
const [formData, setFormData] = React.useState({
startTime: new Date('1/1/2018 9:00 AM'),
endTime: new Date('1/1/2018 5:00 PM'),
});
const handleSubmit = (e: React.FormEvent) => {
e.preventDefault();
console.log('Schedule data:', {
startTime: formData.startTime?.toLocaleTimeString(),
endTime: formData.endTime?.toLocaleTimeString(),
});
};
return (
<form onSubmit={handleSubmit}>
<h3>Schedule Meeting</h3>
<label>Start Time:</label>
<TimePickerComponent
value={formData.startTime}
change={(e: any) => setFormData(prev => ({ ...prev, startTime: e.value }))}
/>
<label style={{ marginTop: '10px' }}>End Time:</label>
<TimePickerComponent
value={formData.endTime}
min={formData.startTime}
change={(e: any) => setFormData(prev => ({ ...prev, endTime: e.value }))}
/>
<ButtonComponent type="submit" isPrimary={true} style={{ marginTop: '15px' }}>
Schedule
</ButtonComponent>
</form>
);
}
export default ScheduleForm;tsx
import { TimePickerComponent } from '@syncfusion/ej2-react-calendars';
import { ButtonComponent } from '@syncfusion/ej2-react-buttons';
import * as React from 'react';
function ScheduleForm() {
const [formData, setFormData] = React.useState({
startTime: new Date('1/1/2018 9:00 AM'),
endTime: new Date('1/1/2018 5:00 PM'),
});
const handleSubmit = (e: React.FormEvent) => {
e.preventDefault();
console.log('日程数据:', {
startTime: formData.startTime?.toLocaleTimeString(),
endTime: formData.endTime?.toLocaleTimeString(),
});
};
return (
<form onSubmit={handleSubmit}>
<h3>安排会议</h3>
<label>开始时间:</label>
<TimePickerComponent
value={formData.startTime}
change={(e: any) => setFormData(prev => ({ ...prev, startTime: e.value }))}
/>
<label style={{ marginTop: '10px' }}>结束时间:</label>
<TimePickerComponent
value={formData.endTime}
min={formData.startTime}
change={(e: any) => setFormData(prev => ({ ...prev, endTime: e.value }))}
/>
<ButtonComponent type="submit" isPrimary={true} style={{ marginTop: '15px' }}>
安排
</ButtonComponent>
</form>
);
}
export default ScheduleForm;Pattern 3: Time Picker with Custom Format
模式3:自定义格式的时间选择器
tsx
import { TimePickerComponent } from '@syncfusion/ej2-react-calendars';
import * as React from 'react';
function TimeFormatDemo() {
const [time12hr, setTime12hr] = React.useState(new Date('1/1/2018 2:30 PM'));
const [time24hr, setTime24hr] = React.useState(new Date('1/1/2018 14:30'));
return (
<div style={{ padding: '20px' }}>
<div>
<h4>12-Hour Format (hh:mm a)</h4>
<TimePickerComponent
value={time12hr}
format="hh:mm a"
change={(e: any) => setTime12hr(e.value)}
/>
<p>Value: {time12hr?.toLocaleTimeString('en-US', { hour12: true })}</p>
</div>
<div style={{ marginTop: '20px' }}>
<h4>24-Hour Format (HH:mm)</h4>
<TimePickerComponent
value={time24hr}
format="HH:mm"
change={(e: any) => setTime24hr(e.value)}
/>
<p>Value: {time24hr?.toLocaleTimeString('en-US', { hour12: false })}</p>
</div>
</div>
);
}
export default TimeFormatDemo;tsx
import { TimePickerComponent } from '@syncfusion/ej2-react-calendars';
import * as React from 'react';
function TimeFormatDemo() {
const [time12hr, setTime12hr] = React.useState(new Date('1/1/2018 2:30 PM'));
const [time24hr, setTime24hr] = React.useState(new Date('1/1/2018 14:30'));
return (
<div style={{ padding: '20px' }}>
<div>
<h4>12小时格式 (hh:mm a)</h4>
<TimePickerComponent
value={time12hr}
format="hh:mm a"
change={(e: any) => setTime12hr(e.value)}
/>
<p>值: {time12hr?.toLocaleTimeString('en-US', { hour12: true })}</p>
</div>
<div style={{ marginTop: '20px' }}>
<h4>24小时格式 (HH:mm)</h4>
<TimePickerComponent
value={time24hr}
format="HH:mm"
change={(e: any) => setTime24hr(e.value)}
/>
<p>值: {time24hr?.toLocaleTimeString('en-US', { hour12: false })}</p>
</div>
</div>
);
}
export default TimeFormatDemo;Pattern 4: Event Handling and State Management
模式4:事件处理与状态管理
tsx
import { TimePickerComponent } from '@syncfusion/ej2-react-calendars';
import * as React from 'react';
function EventTrackingExample() {
const [selectedTime, setSelectedTime] = React.useState<Date | null>(null);
const [eventLog, setEventLog] = React.useState<string[]>([]);
const handleChange = (e: any) => {
setSelectedTime(e.value);
setEventLog(prev => [...prev, `Changed: ${e.value?.toLocaleTimeString()}`]);
};
const handleOpen = (e: any) => {
setEventLog(prev => [...prev, 'Popup opened']);
};
const handleClose = (e: any) => {
setEventLog(prev => [...prev, 'Popup closed']);
};
return (
<div style={{ padding: '20px' }}>
<h3>Time Picker with Event Tracking</h3>
<TimePickerComponent
value={selectedTime}
change={handleChange}
open={handleOpen}
close={handleClose}
placeholder="Select time to track events"
/>
<div style={{ marginTop: '20px', padding: '10px', border: '1px solid #ccc' }}>
<h4>Event Log:</h4>
<ul>
{eventLog.map((event, idx) => (
<li key={idx}>{event}</li>
))}
</ul>
</div>
</div>
);
}
export default EventTrackingExample;tsx
import { TimePickerComponent } from '@syncfusion/ej2-react-calendars';
import * as React from 'react';
function EventTrackingExample() {
const [selectedTime, setSelectedTime] = React.useState<Date | null>(null);
const [eventLog, setEventLog] = React.useState<string[]>([]);
const handleChange = (e: any) => {
setSelectedTime(e.value);
setEventLog(prev => [...prev, `已更改: ${e.value?.toLocaleTimeString()}`]);
};
const handleOpen = (e: any) => {
setEventLog(prev => [...prev, '弹窗已打开']);
};
const handleClose = (e: any) => {
setEventLog(prev => [...prev, '弹窗已关闭']);
};
return (
<div style={{ padding: '20px' }}>
<h3>带事件跟踪的时间选择器</h3>
<TimePickerComponent
value={selectedTime}
change={handleChange}
open={handleOpen}
close={handleClose}
placeholder="选择时间以跟踪事件"
/>
<div style={{ marginTop: '20px', padding: '10px', border: '1px solid #ccc' }}>
<h4>事件日志:</h4>
<ul>
{eventLog.map((event, idx) => (
<li key={idx}>{event}</li>
))}
</ul>
</div>
</div>
);
}
export default EventTrackingExample;Pattern 5: Masked Time Input
模式5:掩码时间输入
tsx
import { TimePickerComponent } from '@syncfusion/ej2-react-calendars';
import * as React from 'react';
function MaskedTimePickerExample() {
const [maskedTime, setMaskedTime] = React.useState(new Date('1/1/2018 10:30 AM'));
return (
<div style={{ padding: '20px' }}>
<h3>Masked Time Input</h3>
<TimePickerComponent
value={maskedTime}
enableMask={true}
format="hh:mm a"
maskPlaceholder={{
hour: 'HH',
minute: 'MM',
second: 'SS',
}}
change={(e: any) => setMaskedTime(e.value)}
placeholder="Enter time (HH:MM AM/PM)"
/>
<p>Masked input helps users enter time in correct format</p>
</div>
);
}
export default MaskedTimePickerExample;tsx
import { TimePickerComponent } from '@syncfusion/ej2-react-calendars';
import * as React from 'react';
function MaskedTimePickerExample() {
const [maskedTime, setMaskedTime] = React.useState(new Date('1/1/2018 10:30 AM'));
return (
<div style={{ padding: '20px' }}>
<h3>掩码时间输入</h3>
<TimePickerComponent
value={maskedTime}
enableMask={true}
format="hh:mm a"
maskPlaceholder={{
hour: 'HH',
minute: 'MM',
second: 'SS',
}}
change={(e: any) => setMaskedTime(e.value)}
placeholder="输入时间 (HH:MM AM/PM)"
/>
<p>掩码输入帮助用户以正确格式输入时间</p>
</div>
);
}
export default MaskedTimePickerExample;Key Props Reference
关键属性参考
| Prop | Type | Default | Purpose |
|---|---|---|---|
| Date | null | Current selected time value |
| string | Based on culture | Time display format (e.g., "HH:mm", "hh:mm a") |
| Date | 00:00 | Minimum selectable time |
| Date | 00:00 | Maximum selectable time |
| number | 30 | Time interval in minutes between list items |
| boolean | true | Enable/disable the component |
| boolean | false | Read-only state (no editing) |
| string | - | Input placeholder text |
| boolean | false | Open popup on input focus |
| boolean | false | Enable masked input mode |
| boolean | false | Enable right-to-left layout |
| boolean | false | Validate input and restrict to valid times |
| boolean | true | Show/hide clear button |
| boolean | false | Mobile full-screen mode |
| string | - | Custom CSS class for styling |
| string | Never | Float label position |
| boolean | true | Allow manual input editing |
| string | 'en-US' | Locale for time formatting |
| Date | - | Default scroll position in popup |
| string/number | - | Component width |
| number | 1000 | Z-index of popup |
| number | - | Server timezone offset for processing |
| object | {} | Custom HTML attributes |
Next Steps:
- Read references/getting-started.md to install and set up your first TimePicker
- Explore references/time-format-and-display.md for format options
- Check references/time-range-and-selection.md for time constraints
- See references/advanced-patterns.md for complex scenarios
| 属性 | 类型 | 默认值 | 用途 |
|---|---|---|---|
| Date | null | 当前选中的时间值 |
| string | 基于文化 | 时间显示格式(例如:"HH:mm"、"hh:mm a") |
| Date | 00:00 | 可选的最小时间 |
| Date | 00:00 | 可选的最大时间 |
| number | 30 | 列表项之间的时间间隔(分钟) |
| boolean | true | 启用/禁用组件 |
| boolean | false | 只读状态(禁止编辑) |
| string | - | 输入框占位文本 |
| boolean | false | 输入框聚焦时打开弹窗 |
| boolean | false | 启用掩码输入模式 |
| boolean | false | 启用从右到左布局 |
| boolean | false | 验证输入并限制为有效时间 |
| boolean | true | 显示/隐藏清除按钮 |
| boolean | false | 移动端全屏模式 |
| string | - | 自定义CSS类用于样式 |
| string | Never | 浮动标签位置 |
| boolean | true | 允许手动输入编辑 |
| string | 'en-US' | 时间格式化的区域设置 |
| Date | - | 弹窗中的默认滚动位置 |
| string/number | - | 组件宽度 |
| number | 1000 | 弹窗的层级 |
| number | - | 处理时使用的服务器时区偏移量 |
| object | {} | 自定义HTML属性 |
下一步:
- 阅读references/getting-started.md安装并设置你的第一个TimePicker
- 探索references/time-format-and-display.md了解格式选项
- 查看references/time-range-and-selection.md了解时间限制
- 查看references/advanced-patterns.md了解复杂场景