syncfusion-react-calendars

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Implementing 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-base
bash
npm install @syncfusion/ej2-react-calendars @syncfusion/ej2-base

Basic 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
    change
    event to sync selected date to React state.
  • 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>
  );
}
注意事项:
  • 使用
    change
    事件将选中的日期同步到React状态。
  • 只需导入一次主题CSS(全局或组件级别)即可为控件设置样式。

Guidance & Patterns

指南与模式

  • Controlled component: keep source-of-truth in React state and update
    value
    via
    change
    event.
  • Multi-selection: use
    isMultiSelection={true}
    with
    values
    prop and
    addDate()
    /
    removeDate()
    methods.
  • Programmatic navigation: use a
    ref
    to call
    navigateTo(view, date)
    — both arguments are required (see references/getting-started-react.md).
  • 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
    role="region"
    and a separate
    aria-live
    region for announcements — these are not direct Calendar props.
  • Week numbers: enable with
    weekNumber={true}
    (the correct prop name).
  • 受控组件: 将数据源保存在React状态中,并通过
    change
    事件更新
    value
  • 多选: 使用
    isMultiSelection={true}
    搭配
    values
    属性和
    addDate()
    /
    removeDate()
    方法。
  • 程序化导航: 使用
    ref
    调用
    navigateTo(view, date)
    — 两个参数均为必填项(请参阅references/getting-started-react.md)。
  • 日期范围: 如需选择范围,请使用DateRangePicker(独立组件)。Calendar本身没有内置的范围高亮模式。
  • 无障碍访问: 使用带有
    role="region"
    的包装元素和单独的
    aria-live
    区域进行提示 — 这些不是Calendar的直接属性。
  • 周数: 通过
    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
    node_modules/@syncfusion/ej2-calendars/styles/
    and are loaded before component styles.
  • React state mismatch: use the
    value
    prop and
    change
    event to keep React state in sync — do not rely on framework-specific bindings.
  • Multiple date selection not working: ensure
    isMultiSelection={true}
    and use
    values
    (not
    value
    ) for the initial array.
  • navigateTo
    not working:
    the method requires two arguments —
    navigateTo(view: CalendarView, date: Date)
    .
  • "Cannot find module": run
    npm install @syncfusion/ej2-react-calendars @syncfusion/ej2-base
    and confirm
    package.json
    .
  • Week numbers not showing: use
    weekNumber={true}
    (not
    showWeekNumber
    ).
  • 样式未生效: 确认CSS导入指向
    node_modules/@syncfusion/ej2-calendars/styles/
    ,且在组件样式之前加载。
  • React状态不匹配: 使用
    value
    属性和
    change
    事件保持React状态同步 — 不要依赖框架特定绑定。
  • 多选不生效: 确保
    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 -
    enableMask
    for segment-by-segment date entry with
    maskPlaceholder
  • Range validation - Min/max dates with
    strictMode
    automatic correction
  • Multiple views - Month, year, and decade views via
    start
    and
    depth
    properties
  • Day cell customization - Disable weekends, highlight special dates via
    renderDayCell
    event
  • Full globalization - 150+ cultures, RTL (
    enableRtl
    ), locale-specific formatting,
    firstDayOfWeek
  • 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(
    enableRtl
    )、区域特定格式化、
    firstDayOfWeek
  • WCAG 2.2合规 - 完整的无障碍支持,包括键盘导航和ARIA属性
  • 表单适配 - 受控组件、React钩子、表单验证集成
  • 程序化控制 -
    show()
    hide()
    focusIn()
    focusOut()
    navigateTo()
    currentView()

Complete API Summary

完整API摘要

Key Properties

关键属性

PropertyTypeDefaultDescription
value
DatenullSelected date
min
Date1900-01-01Minimum selectable date
max
Date2099-12-31Maximum selectable date
format
string | FormatObjectnullDisplay format (e.g.,
"dd/MM/yyyy"
)
inputFormats
string[] | FormatObject[]nullAccepted input formats array
placeholder
stringnullPlaceholder text for the input
enabled
booleantrueEnable or disable the component
readonly
booleanfalseReadonly state
allowEdit
booleantrueAllow editing the input textbox
strictMode
booleanfalseAuto-correct out-of-range dates
showClearButton
booleantrueShow/hide the clear button
showTodayButton
booleantrueShow/hide today button
start
CalendarViewMonthInitial view:
"Month"
,
"Year"
,
"Decade"
depth
CalendarViewMonthDeepest navigation level
enableMask
booleanfalseEnable masked date input
maskPlaceholder
MaskPlaceholderModel{...}Segment placeholders for masked input
enableRtl
booleanfalseRight-to-left rendering
locale
string''Culture/locale code
firstDayOfWeek
number0First day of week (0=Sunday)
weekNumber
booleanfalseShow week numbers
weekRule
WeekRuleFirstDayRule for first week of year
calendarMode
CalendarTypeGregorianCalendar type (Gregorian or Islamic)
dayHeaderFormat
DayHeaderFormatsShortDay name format in header
floatLabelType
FloatLabelTypeNeverFloating label behavior
fullScreenMode
booleanfalseFull screen popup on mobile
openOnFocus
booleanfalseOpen popup on input focus
serverTimezoneOffset
numbernullServer timezone offset
cssClass
stringnullCustom CSS class
htmlAttributes
{ [key: string]: string }{}Additional HTML attributes
keyConfigs
{ [key: string]: string }nullCustom key action mappings
width
number | stringnullComponent width
zIndex
number1000Popup z-index
enablePersistence
booleanfalsePersist state between reloads
属性类型默认值描述
value
Datenull选中的日期
min
Date1900-01-01可选的最小日期
max
Date2099-12-31可选的最大日期
format
string | FormatObjectnull显示格式(例如:
"dd/MM/yyyy"
inputFormats
string[] | FormatObject[]null接受的输入格式数组
placeholder
stringnull输入框占位文本
enabled
booleantrue启用或禁用组件
readonly
booleanfalse只读状态
allowEdit
booleantrue允许编辑输入文本框
strictMode
booleanfalse自动修正超出范围的日期
showClearButton
booleantrue显示/隐藏清除按钮
showTodayButton
booleantrue显示/隐藏今日按钮
start
CalendarViewMonth初始视图:
"Month"
"Year"
"Decade"
depth
CalendarViewMonth最深导航层级
enableMask
booleanfalse启用掩码日期输入
maskPlaceholder
MaskPlaceholderModel{...}掩码输入的分段占位符
enableRtl
booleanfalse从右到左渲染
locale
string''文化/区域代码
firstDayOfWeek
number0一周的第一天(0=周日)
weekNumber
booleanfalse显示周数
weekRule
WeekRuleFirstDay一年第一周的规则
calendarMode
CalendarTypeGregorian日历类型(公历或伊斯兰历)
dayHeaderFormat
DayHeaderFormatsShort表头中的日期名称格式
floatLabelType
FloatLabelTypeNever浮动标签行为
fullScreenMode
booleanfalse移动端全屏弹窗
openOnFocus
booleanfalse输入框聚焦时打开弹窗
serverTimezoneOffset
numbernull服务器时区偏移量
cssClass
stringnull自定义CSS类
htmlAttributes
{ [key: string]: string }{}额外的HTML属性
keyConfigs
{ [key: string]: string }null自定义按键操作映射
width
number | stringnull组件宽度
zIndex
number1000弹窗层级
enablePersistence
booleanfalse刷新后保留状态

Methods

方法

MethodReturnsDescription
show()
voidOpens the calendar popup
hide()
voidCloses the calendar popup
focusIn()
voidSets focus to the component
focusOut()
voidRemoves focus from the component
navigateTo(view, date)
voidNavigates to a specific view and date
currentView()
stringReturns the current calendar view name
getPersistData()
stringGets persisted state data
removeDate(dates)
voidRemoves date(s) from the values
destroy()
voidDestroys the component
方法返回值描述
show()
void打开日历弹窗
hide()
void关闭日历弹窗
focusIn()
void设置组件焦点
focusOut()
void移除组件焦点
navigateTo(view, date)
void导航到指定视图和日期
currentView()
string返回当前日历视图名称
getPersistData()
string获取持久化状态数据
removeDate(dates)
void从值中移除日期
destroy()
void销毁组件

Events

事件

EventArgs TypeDescription
change
ChangedEventArgsFires when the selected date changes
focus
FocusEventArgsFires when input gains focus
blur
BlurEventArgsFires when input loses focus
open
PreventableEventArgs | PopupObjectArgsFires when the popup opens
close
PreventableEventArgs | PopupObjectArgsFires when the popup closes
cleared
ClearedEventArgsFires when value is cleared
created
ObjectFires when component is created
destroyed
ObjectFires when component is destroyed
navigated
NavigatedEventArgsFires when calendar view is navigated
renderDayCell
RenderDayCellEventArgsFires when each day cell is rendered
事件参数类型描述
change
ChangedEventArgs选中日期改变时触发
focus
FocusEventArgs输入框获得焦点时触发
blur
BlurEventArgs输入框失去焦点时触发
open
PreventableEventArgs | PopupObjectArgs弹窗打开时触发
close
PreventableEventArgs | PopupObjectArgs弹窗关闭时触发
cleared
ClearedEventArgs值被清除时触发
created
Object组件创建时触发
destroyed
Object组件销毁时触发
navigated
NavigatedEventArgs日历视图导航时触发
renderDayCell
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
  • enableMask
    property for structured segment-by-segment date input
  • maskPlaceholder
    for custom segment placeholder text
  • Date masking patterns for input guidance
  • strictMode
    property behavior and enforcement
  • 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
    DatePickerComponent
    from
    @syncfusion/ej2-react-calendars
  • Import all required CSS themes (base, buttons, inputs, popups, calendars)
  • Use
    value
    prop for the current date (can be null or Date object)
  • Use
    change
    event (not
    onChange
    ) to update React state — this is the Syncfusion event name
  • 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-calendars
    导入
    DatePickerComponent
  • 导入所有必需的CSS主题(base、buttons、inputs、popups、calendars)
  • 使用
    value
    属性设置当前日期(可为null或Date对象)
  • 使用
    change
    事件(而非
    onChange
    )更新React状态 — 这是Syncfusion的事件名称
  • 点击或按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;
<!-- Pattern 3 removed: examples using non-API props (e.g., `disabledDates`) deleted to match authoritative API reference -->
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;
<!-- 模式3已移除:使用非API属性(如`disabledDates`)的示例已删除,以匹配权威API参考 -->

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:
    startDate
    : Type:
    Date
    — Default:
    null
    — Initial start date of the range.
  • Prop:
    endDate
    : Type:
    Date
    — Default:
    null
    — Initial end date of the range.
  • Prop:
    min
    : Type:
    Date
    — Default:
    new Date(1900, 0, 1)
    — Minimum selectable date.
  • Prop:
    max
    : Type:
    Date
    — Default:
    new Date(2099, 11, 31)
    — Maximum selectable date.
  • Prop:
    value
    : Type:
    Date[] | DateRange
    — Default:
    null
    — Gets or sets the start and end date.
  • Prop:
    format
    : Type:
    string | RangeFormatObject
    — Default:
    null
    — Date display and input format.
  • Prop:
    placeholder
    : Type:
    string
    — Default:
    null
    — Input placeholder text.
  • Prop:
    enabled
    : Type:
    boolean
    — Default:
    true
    — Enables or disables the component (use
    enabled
    , not
    disabled
    ).
  • Prop:
    readonly
    : Type:
    boolean
    — Default:
    false
    — Read-only state; prevents editing.
  • Prop:
    allowEdit
    : Type:
    boolean
    — Default:
    true
    — Allow manual text editing of the input.
  • Prop:
    cssClass
    : Type:
    string
    — Default:
    ''
    — Adds a custom CSS class to the root element.
  • Prop:
    floatLabelType
    : Type:
    FloatLabelType | string
    — Default:
    Never
    — Float label behavior (Never, Always, Auto).
  • Prop:
    separator
    : Type:
    string
    — Default:
    '-'
    — Separator string between start and end date in the input.
  • Prop:
    locale
    : Type:
    string
    — Default:
    'en-US'
    — Locale used for formatting and localization.
  • Prop:
    inputFormats
    : Type:
    string[] | RangeFormatObject[]
    — Default:
    null
    — Acceptable input parsing formats.
  • Prop:
    keyConfigs
    : Type:
    object
    — Default:
    null
    — Custom keyboard shortcuts mapping.
  • Prop:
    firstDayOfWeek
    : Type:
    number
    — Default:
    null
    — First day of week for calendar rendering.
  • Prop:
    dayHeaderFormat
    : Type:
    DayHeaderFormats
    — Default:
    Short
    — Day name format in header.
  • Prop:
    start
    : Type:
    CalendarView
    — Default:
    Month
    — Initial calendar view when popup opens.
  • Prop:
    depth
    : Type:
    CalendarView
    — Default:
    Month
    — Maximum navigation depth for the calendar.
  • Prop:
    weekNumber
    : Type:
    boolean
    — Default:
    false
    — Show week numbers in calendar rows.
  • Prop:
    weekRule
    : Type:
    WeekRule
    — Default:
    FirstDay
    — Rule that defines first week of the year.
  • Prop:
    minDays
    : Type:
    number
    — Default:
    null
    — Minimum allowed span of days in a selection.
  • Prop:
    maxDays
    : Type:
    number
    — Default:
    null
    — Maximum allowed span of days in a selection.
  • Prop:
    strictMode
    : Type:
    boolean
    — Default:
    false
    — When true, only valid ranges can be entered.
  • Prop:
    showClearButton
    : Type:
    boolean
    — Default:
    true
    — Toggle visibility of the clear button.
  • Prop:
    fullScreenMode
    : Type:
    boolean
    — Default:
    false
    — Use full-screen popup on mobile.
  • Prop:
    htmlAttributes
    : Type:
    { [key: string]: string }
    — Default:
    {}
    — Additional HTML attributes applied to the component element.
  • Prop:
    serverTimezoneOffset
    : Type:
    number
    — Default:
    null
    — Server timezone offset in minutes for initial value processing.
  • Prop:
    width
    : Type:
    number | string
    — Default:
    ''
    — Width of the component input.
  • Prop:
    zIndex
    : Type:
    number
    — Default:
    1000
    — z-index for popup element.

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
    — 浮动标签行为(Never、Always、Auto)。
  • 属性:
    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
    — 默认值:
    false
    — 为true时,仅允许输入有效范围。
  • 属性:
    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快速入门

  1. Install package:
bash
npm install @syncfusion/ej2-react-calendars
  1. Import styles (in
    index.css
    or component CSS):
css
@import '../node_modules/@syncfusion/ej2-base/styles/material3.css';
@import '../node_modules/@syncfusion/ej2-calendars/styles/material3.css';
  1. 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>
  );
}
  1. 安装包:
bash
npm install @syncfusion/ej2-react-calendars
  1. 导入样式(在
    index.css
    或组件CSS中):
css
@import '../node_modules/@syncfusion/ej2-base/styles/material3.css';
@import '../node_modules/@syncfusion/ej2-calendars/styles/material3.css';
  1. 极简函数示例(
    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
    value
    and update on
    change
    .
  • Range enforcement: use
    min
    and
    max
    for dates,
    minTime
    /
    maxTime
    for times.
  • Masked input: enable with
    enableMask
    and provide
    maskPlaceholder
    .
  • Localization: set
    locale
    or use global culture settings.
  • Keyboard-first: provide
    keyConfigs
    for custom shortcuts.
  • 受控值: 绑定
    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
    completion-status.json
    , or produce publish-ready artifacts.
  • 所有参考文件已创建并通过官方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

关键属性参考

PropTypeDefaultPurpose
value
DatenullCurrent selected time value
format
stringBased on cultureTime display format (e.g., "HH:mm", "hh:mm a")
min
Date00:00Minimum selectable time
max
Date00:00Maximum selectable time
step
number30Time interval in minutes between list items
enabled
booleantrueEnable/disable the component
readonly
booleanfalseRead-only state (no editing)
placeholder
string-Input placeholder text
openOnFocus
booleanfalseOpen popup on input focus
enableMask
booleanfalseEnable masked input mode
enableRtl
booleanfalseEnable right-to-left layout
strictMode
booleanfalseValidate input and restrict to valid times
showClearButton
booleantrueShow/hide clear button
fullScreenMode
booleanfalseMobile full-screen mode
cssClass
string-Custom CSS class for styling
floatLabelType
stringNeverFloat label position
allowEdit
booleantrueAllow manual input editing
locale
string'en-US'Locale for time formatting
scrollTo
Date-Default scroll position in popup
width
string/number-Component width
zIndex
number1000Z-index of popup
serverTimezoneOffset
number-Server timezone offset for processing
htmlAttributes
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
属性类型默认值用途
value
Datenull当前选中的时间值
format
string基于文化时间显示格式(例如:"HH:mm"、"hh:mm a")
min
Date00:00可选的最小时间
max
Date00:00可选的最大时间
step
number30列表项之间的时间间隔(分钟)
enabled
booleantrue启用/禁用组件
readonly
booleanfalse只读状态(禁止编辑)
placeholder
string-输入框占位文本
openOnFocus
booleanfalse输入框聚焦时打开弹窗
enableMask
booleanfalse启用掩码输入模式
enableRtl
booleanfalse启用从右到左布局
strictMode
booleanfalse验证输入并限制为有效时间
showClearButton
booleantrue显示/隐藏清除按钮
fullScreenMode
booleanfalse移动端全屏模式
cssClass
string-自定义CSS类用于样式
floatLabelType
stringNever浮动标签位置
allowEdit
booleantrue允许手动输入编辑
locale
string'en-US'时间格式化的区域设置
scrollTo
Date-弹窗中的默认滚动位置
width
string/number-组件宽度
zIndex
number1000弹窗的层级
serverTimezoneOffset
number-处理时使用的服务器时区偏移量
htmlAttributes
object{}自定义HTML属性

下一步:
  • 阅读references/getting-started.md安装并设置你的第一个TimePicker
  • 探索references/time-format-and-display.md了解格式选项
  • 查看references/time-range-and-selection.md了解时间限制
  • 查看references/advanced-patterns.md了解复杂场景