• DatePicker 日期选择框

    输入或选择日期的控件。

    何时使用

    当用户需要输入一个日期,可以点击标准输入框,弹出日期面板进行选择。

    代码演示

    最简单的用法,在浮层中可以选择或者输入日期。
    expand code expand code
    import { DatePicker } from 'choerodon-ui';
    const { MonthPicker, RangePicker, WeekPicker } = DatePicker;
    
    function onChange(date, dateString) {
      console.log(date, dateString);
    }
    
    ReactDOM.render(
      <div>
        <DatePicker onChange={onChange} label="日期框" />
        <br />
        <MonthPicker onChange={onChange} placeholder="Select month" />
        <br />
        <RangePicker onChange={onChange} />
        <br />
        <WeekPicker onChange={onChange} placeholder="Select week" label="选择周" />
      </div>,
      mountNode);
    
    三种大小的输入框,若不设置,则为 default
    expand code expand code
    import { DatePicker, Radio } from 'choerodon-ui';
    const { MonthPicker, RangePicker, WeekPicker } = DatePicker;
    
    class PickerSizesDemo extends React.Component {
      state = {
        size: 'default',
      };
    
      handleSizeChange = (e) => {
        this.setState({ size: e.target.value });
      }
    
      render() {
        const { size } = this.state;
        return (
          <div>
            <Radio.Group value={size} onChange={this.handleSizeChange}>
              <Radio.Button value="large">Large</Radio.Button>
              <Radio.Button value="default">Default</Radio.Button>
              <Radio.Button value="small">Small</Radio.Button>
            </Radio.Group>
            <br /><br />
            <DatePicker size={size} />
            <br />
            <MonthPicker size={size} placeholder="Select Month" />
            <br />
            <RangePicker size={size} />
            <br />
            <WeekPicker size={size} placeholder="Select Week" />
          </div>
        );
      }
    }
    
    ReactDOM.render(<PickerSizesDemo />, mountNode);
    
    选择框的不可用状态。
    expand code expand code
    import { DatePicker } from 'choerodon-ui';
    import moment from 'moment';
    const { MonthPicker, RangePicker } = DatePicker;
    
    const dateFormat = 'YYYY-MM-DD';
    ReactDOM.render(
      <div>
        <DatePicker defaultValue={moment('2015-06-06', dateFormat)} disabled />
        <br />
        <MonthPicker defaultValue={moment('2015-06', 'YYYY-MM')} disabled />
        <br />
        <RangePicker
          defaultValue={[moment('2015-06-06', dateFormat), moment('2015-06-06', dateFormat)]}
          disabled
        />
      </div>,
      mountNode);
    
    RangePicker 无法满足业务需求时,可以使用两个 DatePicker 实现类似的功能。 > * 通过设置 disabledDate 方法,来约束开始和结束日期。 > * 通过 open onOpenChange 来优化交互。
    expand code expand code
    import { DatePicker } from 'choerodon-ui';
    
    class DateRange extends React.Component {
      state = {
        startValue: null,
        endValue: null,
        endOpen: false,
      };
    
      disabledStartDate = (startValue) => {
        const endValue = this.state.endValue;
        if (!startValue || !endValue) {
          return false;
        }
        return startValue.valueOf() > endValue.valueOf();
      }
    
      disabledEndDate = (endValue) => {
        const startValue = this.state.startValue;
        if (!endValue || !startValue) {
          return false;
        }
        return endValue.valueOf() <= startValue.valueOf();
      }
    
      onChange = (field, value) => {
        this.setState({
          [field]: value,
        });
      }
    
      onStartChange = (value) => {
        this.onChange('startValue', value);
      }
    
      onEndChange = (value) => {
        this.onChange('endValue', value);
      }
    
      handleStartOpenChange = (open) => {
        if (!open) {
          this.setState({ endOpen: true });
        }
      }
    
      handleEndOpenChange = (open) => {
        this.setState({ endOpen: open });
      }
    
      render() {
        const { startValue, endValue, endOpen } = this.state;
        return (
          <div>
            <DatePicker
              disabledDate={this.disabledStartDate}
              showTime
              format="YYYY-MM-DD HH:mm:ss"
              value={startValue}
              placeholder="Start"
              onChange={this.onStartChange}
              onOpenChange={this.handleStartOpenChange}
            />
            <DatePicker
              disabledDate={this.disabledEndDate}
              showTime
              format="YYYY-MM-DD HH:mm:ss"
              value={endValue}
              placeholder="End"
              onChange={this.onEndChange}
              open={endOpen}
              onOpenChange={this.handleEndOpenChange}
            />
          </div>
        );
      }
    }
    
    ReactDOM.render(<DateRange />, mountNode);
    
    在浮层中加入额外的页脚,以满足某些定制信息的需求。
    expand code expand code
    import { DatePicker } from 'choerodon-ui';
    const { RangePicker, MonthPicker } = DatePicker;
    
    ReactDOM.render(
      <div>
        <DatePicker renderExtraFooter={() => 'extra footer'} />
        <DatePicker renderExtraFooter={() => 'extra footer'} showTime />
        <RangePicker renderExtraFooter={() => 'extra footer'} />
        <RangePicker renderExtraFooter={() => 'extra footer'} showTime />
        <MonthPicker renderExtraFooter={() => 'extra footer'} placeholder="Select month" />
      </div>,
      mountNode);
    
    使用 dateRender 可以自定义日期单元格的内容和样式。
    expand code expand code
    import { DatePicker } from 'choerodon-ui';
    const { RangePicker } = DatePicker;
    
    ReactDOM.render(
      <div>
        <DatePicker
          dateRender={(current) => {
            const style = {};
            if (current.date() === 1) {
              style.border = '1px solid #1890ff';
              style.borderRadius = '50%';
            }
            return (
              <div className="ant-calendar-date" style={style}>
                {current.date()}
              </div>
            );
          }}
        />
        <RangePicker
          dateRender={(current) => {
            const style = {};
            if (current.date() === 1) {
              style.border = '1px solid #1890ff';
              style.borderRadius = '50%';
            }
            return (
              <div className="ant-calendar-date" style={style}>
                {current.date()}
              </div>
            );
          }}
        />
      </div>,
      mountNode);
    
    使用 format 属性,可以自定义日期显示格式。
    expand code expand code
    import { DatePicker } from 'choerodon-ui';
    import moment from 'moment';
    const { MonthPicker, RangePicker } = DatePicker;
    
    const dateFormat = 'YYYY/MM/DD';
    const monthFormat = 'YYYY/MM';
    ReactDOM.render(
      <div>
        <DatePicker defaultValue={moment('2015/01/01', dateFormat)} format={dateFormat} />
        <br />
        <MonthPicker defaultValue={moment('2015/01', monthFormat)} format={monthFormat} />
        <br />
        <RangePicker
          defaultValue={[moment('2015/01/01', dateFormat), moment('2015/01/01', dateFormat)]}
          format={dateFormat}
        />
      </div>,
      mountNode);
    
    增加选择时间功能,当 showTime 为一个对象时,其属性会传递给内建的 TimePicker
    expand code expand code
    import { DatePicker } from 'choerodon-ui';
    const { RangePicker } = DatePicker;
    
    function onChange(value, dateString) {
      console.log('Selected Time: ', value);
      console.log('Formatted Selected Time: ', dateString);
    }
    
    function onOk(value) {
      console.log('onOk: ', value);
    }
    
    ReactDOM.render(
      <div>
        <DatePicker
          showTime
          format="YYYY-MM-DD HH:mm:ss"
          placeholder="Select Time"
          onChange={onChange}
          onOk={onOk}
        />
        <br />
        <RangePicker
          showTime={{ format: 'HH:mm' }}
          format="YYYY-MM-DD HH:mm"
          placeholder={['Start Time', 'End Time']}
          onChange={onChange}
          onOk={onOk}
        />
      </div>,
      mountNode);
    
    可用 disabledDatedisabledTime 分别禁止选择部分日期和时间,其中 disabledTime 需要和 showTime 一起使用。
    expand code expand code
    import moment from 'moment';
    import { DatePicker } from 'choerodon-ui';
    const { MonthPicker, RangePicker } = DatePicker;
    
    function range(start, end) {
      const result = [];
      for (let i = start; i < end; i++) {
        result.push(i);
      }
      return result;
    }
    
    function disabledDate(current) {
      // Can not select days before today and today
      return current && current < moment().endOf('day');
    }
    
    function disabledDateTime() {
      return {
        disabledHours: () => range(0, 24).splice(4, 20),
        disabledMinutes: () => range(30, 60),
        disabledSeconds: () => [55, 56],
      };
    }
    
    function disabledRangeTime(_, type) {
      if (type === 'start') {
        return {
          disabledHours: () => range(0, 60).splice(4, 20),
          disabledMinutes: () => range(30, 60),
          disabledSeconds: () => [55, 56],
        };
      }
      return {
        disabledHours: () => range(0, 60).splice(20, 4),
        disabledMinutes: () => range(0, 31),
        disabledSeconds: () => [55, 56],
      };
    }
    
    ReactDOM.render(
      <div>
        <DatePicker
          format="YYYY-MM-DD HH:mm:ss"
          disabledDate={disabledDate}
          disabledTime={disabledDateTime}
          showTime={{ defaultValue: moment('00:00:00', 'HH:mm:ss') }}
        />
        <br />
        <MonthPicker disabledDate={disabledDate} placeholder="Select month" />
        <br />
        <RangePicker
          disabledDate={disabledDate}
          disabledTime={disabledRangeTime}
          showTime={{
            hideDisabledOptions: true,
            defaultValue: [moment('00:00:00', 'HH:mm:ss'), moment('11:59:59', 'HH:mm:ss')],
          }}
          format="YYYY-MM-DD HH:mm:ss"
        />
      </div>,
      mountNode
    );
    
    RangePicker 可以设置常用的 预设范围 提高用户体验。
    expand code expand code
    import { DatePicker } from 'choerodon-ui';
    const RangePicker = DatePicker.RangePicker;
    
    function onChange(dates, dateStrings) {
      console.log('From: ', dates[0], ', to: ', dates[1]);
      console.log('From: ', dateStrings[0], ', to: ', dateStrings[1]);
    }
    
    ReactDOM.render(
      <div>
        <RangePicker
          ranges={{ Today: [moment(), moment()], 'This Month': [moment(), moment().endOf('month')] }}
          onChange={onChange}
        />
        <br />
        <RangePicker
          ranges={{ Today: [moment(), moment()], 'This Month': [moment(), moment().endOf('month')] }}
          showTime
          format="YYYY/MM/DD HH:mm:ss"
          onChange={onChange}
        />
      </div>,
      mountNode
    );
    
    通过组合 modeonPanelChange 控制要展示的面板。
    expand code expand code
    import { DatePicker } from 'choerodon-ui';
    const { RangePicker } = DatePicker;
    
    class ControlledDatePicker extends React.Component {
      state = { mode: 'time' };
    
      handleOpenChange = (open) => {
        if (open) {
          this.setState({ mode: 'time' });
        }
      }
    
      handlePanelChange = (value, mode) => {
        this.setState({ mode });
      }
    
      render() {
        return (
          <DatePicker
            mode={this.state.mode}
            showTime
            onOpenChange={this.handleOpenChange}
            onPanelChange={this.handlePanelChange}
          />
        );
      }
    }
    
    class ControlledRangePicker extends React.Component {
      state = {
        mode: ['month', 'month'],
        value: [],
      };
    
      handlePanelChange = (value, mode) => {
        this.setState({
          value,
          mode: [
            mode[0] === 'date' ? 'month' : mode[0],
            mode[1] === 'date' ? 'month' : mode[1],
          ],
        });
      }
    
      render() {
        const { value, mode } = this.state;
        return (
          <RangePicker
            placeholder={['Start month', 'End month']}
            format="YYYY-MM"
            value={value}
            mode={mode}
            onPanelChange={this.handlePanelChange}
          />
        );
      }
    }
    
    ReactDOM.render(
      <div>
        <ControlledDatePicker />
        <br />
        <ControlledRangePicker />
      </div>,
      mountNode);
    

    API

    日期类组件包括以下四种形式。

    注意:DatePicker、MonthPicker、RangePicker、WeekPicker 部分 locale 是从 value 中读取,所以请先正确设置 moment 的 locale。

    // 默认语言为 en-US,如果你需要设置其他语言,推荐在入口文件全局设置 locale
    // import moment from 'moment';
    // import 'moment/locale/zh-cn';
    // moment.locale('zh-cn');
    
    <DatePicker defaultValue={moment('2015-01-01', 'YYYY-MM-DD')} />
    

    共同的 API

    以下 API 为 DatePicker、MonthPicker、RangePicker, WeekPicker 共享的 API。

    参数说明类型默认值
    allowClear是否显示清除按钮booleantrue
    autoFocus自动获取焦点booleanfalse
    className选择器 classNamestring
    dateRender自定义日期单元格的内容function(currentDate: moment, today: moment) => React.ReactNode-
    disabled禁用booleanfalse
    disabledDate不可选择的日期(currentDate: moment) => boolean
    getCalendarContainer定义浮层的容器,默认为 body 上新建 divfunction(trigger)
    locale国际化配置object默认配置
    open控制弹层是否展开boolean-
    placeholder输入框提示文字string|RangePicker[]-
    popupStyle额外的弹出日历样式object{}
    dropdownClassName额外的弹出日历 classNamestring-
    size输入框大小,large 高度为 40px,small 为 24px,默认是 32pxstring
    style自定义输入框样式object{}
    onOpenChange弹出日历和关闭日历的回调function(status)

    共同的方法

    名称描述
    blur()移除焦点
    focus()获取焦点

    DatePicker

    参数说明类型默认值
    defaultValue默认日期moment
    disabledTime不可选择的时间function(date)
    format展示的日期格式,配置参考 moment.jsstring“YYYY-MM-DD”
    renderExtraFooter在面板中添加额外的页脚() => React.ReactNode-
    showTime增加时间选择功能Object|booleanTimePicker Options
    showTime.defaultValue设置用户选择日期时默认的时分秒,例子momentmoment()
    showToday是否展示“今天”按钮booleantrue
    value日期moment
    onChange时间发生变化的回调function(date: moment, dateString: string)
    onOk点击确定按钮的回调function()-

    MonthPicker

    参数说明类型默认值
    defaultValue默认日期moment
    format展示的日期格式,配置参考 moment.jsstring“YYYY-MM”
    monthCellContentRender自定义的月份内容渲染方法function(date, locale): ReactNode-
    renderExtraFooter在面板中添加额外的页脚() => React.ReactNode-
    value日期moment
    onChange时间发生变化的回调,发生在用户选择时间时function(date: moment, dateString: string)-

    WeekPicker

    参数说明类型默认值
    defaultValue默认日期moment-
    format展示的日期格式,配置参考 moment.jsstring“YYYY-wo”
    value日期moment-
    onChange时间发生变化的回调,发生在用户选择时间时function(date: moment, dateString: string)-

    RangePicker

    参数说明类型默认值
    defaultValue默认日期moment[]
    disabledTime不可选择的时间function(dates: [moment, moment], partial: `‘start’‘end’`)
    format展示的日期格式string“YYYY-MM-DD HH:mm:ss”
    ranges      预设时间范围快捷选择{ [range: string]: moment[] } | () => { [range: string]: moment[] }
    renderExtraFooter在面板中添加额外的页脚() => React.ReactNode-
    showTime增加时间选择功能Object|booleanTimePicker Options
    showTime.defaultValue设置用户选择日期时默认的时分秒,例子moment[][moment(), moment()]
    value日期moment[]
    onCalendarChange待选日期发生变化的回调function(dates: [moment, moment], dateStrings: [string, string])
    onChange日期范围发生变化的回调function(dates: [moment, moment], dateStrings: [string, string])
    onOk点击确定按钮的回调function()-