块编辑器开发文档

💡 云策文档标注

概述

DatePicker 是一个 React 组件,用于渲染日期选择日历,可独立使用或作为 DateTimePicker 的一部分。它支持自定义日期初始化、事件处理和验证。

关键要点

  • DatePicker 是一个 React 组件,用于日期选择,可独立或集成使用。
  • 组件接受多个 props,包括 currentDate、onChange、events、isInvalidDate、onMonthPreviewed 和 startOfWeek。
  • currentDate 用于设置初始日期,支持 Date、string、number 或 null 类型,默认值为当天日期。
  • onChange 回调函数在日期选择时触发,接收当前日期作为参数。
  • events 属性允许显示事件点,isInvalidDate 用于验证日期有效性。
  • onMonthPreviewed 在切换月份时调用,startOfWeek 设置周起始日。

代码示例

import { useState } from 'react';
import { DatePicker } from '@wordpress/components';

const MyDatePicker = () => {
    const [ date, setDate ] = useState( new Date() );

    return (
        <DatePicker
            currentDate={ date }
            onChange={ ( newDate ) => setDate( newDate ) }
        />
    );
};

📄 原文内容

DatePicker is a React component that renders a calendar for date selection. It can be used independently or as part of the DateTimePicker component.

Usage

Render a DatePicker.

import { useState } from 'react';
import { DatePicker } from '@wordpress/components';

const MyDatePicker = () => {
    const [ date, setDate ] = useState( new Date() );

    return (
        <DatePicker
            currentDate={ date }
            onChange={ ( newDate ) => setDate( newDate ) }
        />
    );
};

Props

The component accepts the following props:

currentDate: Date | string | number | null

The current date at initialization. Optionally pass in a null value to specify no date is currently selected.

  • Required: No
  • Default: today’s date

onChange: ( date: string ) => void

The function called when a new date has been selected. It is passed the currentDate as an argument.

  • Required: No

events: { date: Date }[]

List of events to show in the date picker. Each event will appear as a dot on the day of the event.

  • Required: No

isInvalidDate: ( date: Date ) => boolean

A callback function which receives a Date object representing a day as an argument, and should return a Boolean to signify if the day is valid or not.

  • Required: No

onMonthPreviewed: ( date: string ) => void

A callback invoked when selecting the previous/next month in the date picker. The callback receives the new month date in the ISO format as an argument.

  • Required: No

startOfWeek: 0 | 1 | 2 | 3 | 4 | 5 | 6

The day that the week should start on. 0 for Sunday, 1 for Monday, etc.

  • Required: No
  • Default: 0