React-Antd-表单-时间类控件

文档地址: 链接.

时间类组件的 value 类型为 moment 对象,所以在提交服务器前需要预处理。

import {Form,DatePicker,TimePicker,Button,Select,Space,Input,Row,Col} from "antd";
import moment from "moment";
import { Fragment, useState } from "react";
export default function App() {
  let [form] = Form.useForm();
  const [dates, setDates] = useState([]);
  const [hackValue, setHackValue] = useState([]);
  const [value, setValue] = useState();
  function range(start, end) {
    const result = [];
    for (let i = start; i < end; i++) {
      result.push(i);
    }
    return result;
  }
  return (
    <div>
      <Form
        form={form}
        name="time_related_controls"
        initialValues={{
          basicDataPicker: moment("2021-11-04"),
          basicMonthPicker: moment("2021-11-04"),
          basicWeekPicker: moment("2021-11-04"),
          basicQuarterPicker: moment("2021-11-04"),
          basicYearPicker: moment("2021-11-04"),

          rangePicker: [moment("2021-11-04"), moment("2021-12-04")],
          rangePickerShowTime: [
            moment("2021-11-04 12:12:12"),
            moment("2021-12-04 06:06:06"),
          ],
          rangePickerWeek: [
            moment("2021-11-04 12:12:12"),
            moment("2021-12-04 06:06:06"),
          ],
          rangePickerMonth: [
            moment("2021-11-04 12:12:12"),
            moment("2021-12-04 06:06:06"),
          ],
          rangePickerYear: [
            moment("2020-11-04 12:12:12"),
            moment("2021-12-04 06:06:06"),
          ],

          selectType: "month",
          YYYYMMDD: moment("2020-11-04 12:12:12"),
          DDMMYYYY: moment("2020-11-04 12:12:12"),
          DDMMYY: moment("2020-11-04 12:12:12"),
          YYYYMM: moment("2020-11-04 12:12:12"),
          weekMMDD: moment("2020-11-04 12:12:12"),
          customFormatYYYYMMDD: moment("2020-11-04 12:12:12"),
          rangePickerYYYYMMDD: [
            moment("2020-11-04 12:12:12"),
            moment("2021-11-04 12:12:12"),
          ],

          datePickerShowTime: moment("2020-11-04 12:12:12"),
          rangePickerShowTime: [
            moment("2020-11-04 12:12:12"),
            moment("2021-11-04 12:12:12"),
          ],

          disabledDatePicker: moment("2020-11-04 12:12:12"),
          disabledDatePickerMonth: moment("2020-11-04 12:12:12"),
          disabledDatePickerRangePicker: [
            moment("2020-11-04 12:12:12"),
            moment("2021-11-04 12:12:12"),
          ],
          disabledDatePickerRangePicker1: [
            moment("2020-11-04 12:12:12"),
            moment("2021-11-04 12:12:12"),
          ],

          disableHourMinutesSecond: moment("2021-11-30 03:03:03"),
          disableMonth: moment("2021-11-30 03:03:03"),
          disabledDatePickerInner: moment("2021-11-30 03:03:03"),
          disabledStartEnd: [
            moment("2021-11-26 03:03:03"),
            moment("2021-11-30 03:03:03"),
          ],
          shortcutKeyDate: [
            moment("2021-11-26 03:03:03"),
            moment("2021-11-30 03:03:03"),
          ],
          shortcutKeyDateTime: [
            moment("2021-11-26 03:03:03"),
            moment("2021-11-30 03:03:03"),
          ],
          extralFooterDatePicker: moment("2021-11-26 03:03:03"),
          extralFooterDatePickerTime: moment("2021-11-26 03:03:03"),
          extralFooterDatePickerRangePicker: [
            moment("2021-11-26 03:03:03"),
            moment("2021-11-30 03:03:03"),
          ],
          extralFooterDatePickerRangePickerTime: [
            moment("2021-11-26 03:03:03"),
            moment("2021-11-30 03:03:03"),
          ],
          extralFooterDatePickerRangePickerMonth: [
            moment("2021-11-26 03:03:03"),
            moment("2021-11-30 03:03:03"),
          ],
          customDate: moment("2021-11-26 03:03:03"),
          customDateRangePicker: [
            moment("2021-11-26 03:03:03"),
            moment("2021-11-30 03:03:03"),
          ],
          selectType: "week",
          selectVal: moment("2021-11-26 03:03:03"),
          notExceedSevenDay: [moment("2021-11-22 03:03:03"),moment("2021-11-26 03:03:03")],
        }}
        onFinish={(values) => {
          console.log(values);
          // console.log(values["dataPicker"].format("YYYY-MM-DD")); //2021-11-04
          // console.log(values["dataTimePicker"].format("YYYY-MM-DD HH:mm:ss")); //2021-11-19 09:59:27
          // console.log(values["monthPicker"].format("YYYY-MM")); //2021-06
          // console.log(
          //   values["rangePicker"][0].format("YYYY-MM-DD"),
          //   values["rangePicker"][1].format("YYYY-MM-DD")
          // ); //2021-11-01 2021-11-19
          // console.log(
          //   values["rangeTimePicker"][0].format("YYYY-MM-DD HH:mm:ss"),
          //   values["rangePicker"][1].format("YYYY-MM-DD HH:mm:ss")
          // ); //2021-11-01 10:23:17 2021-11-19 10:23:17
          // console.log(values["timePicker"].format("HH:mm:ss")); //10:26:32
        }}
      >
        <Form.Item label="基本">
          {/* 最简单的用法,在浮层中可以选择或者输入日期。 */}
          <Form.Item
            label="日期"
            name="basicDataPicker"
            rules={[
              {
                required: true,
              },
            ]}
          >
            <DatePicker />
          </Form.Item>
          <Form.Item
            label="日期月份"
            name="basicMonthPicker"
            rules={[
              {
                required: true,
              },
            ]}
          >
            <DatePicker picker="month" />
          </Form.Item>
          <Form.Item
            label="日期周"
            name="basicWeekPicker"
            rules={[
              {
                required: true,
              },
            ]}
          >
            <DatePicker picker="week" />
          </Form.Item>
          <Form.Item
            label="日期季度"
            name="basicQuarterPicker"
            rules={[
              {
                required: true,
              },
            ]}
          >
            <DatePicker picker="quarter" />
          </Form.Item>
          <Form.Item
            label="日期年"
            name="basicYearPicker"
            rules={[
              {
                required: true,
              },
            ]}
          >
            <DatePicker picker="year" />
          </Form.Item>
        </Form.Item>
        <Form.Item label="范围选择器">
          {/* 通过设置 picker 属性,指定范围选择器类型。 */}
          <Form.Item
            label="日期"
            name="rangePicker"
            rules={[
              {
                required: true,
              },
            ]}
          >
            <DatePicker.RangePicker />
          </Form.Item>
          <Form.Item
            label="日期时间"
            name="rangePickerShowTime"
            rules={[
              {
                required: true,
              },
            ]}
          >
            <DatePicker.RangePicker showTime />
          </Form.Item>
          <Form.Item
            label="日期周"
            name="rangePickerWeek"
            rules={[
              {
                required: true,
              },
            ]}
          >
            <DatePicker.RangePicker picker="week" />
          </Form.Item>
          <Form.Item
            label="日期月"
            name="rangePickerMonth"
            rules={[
              {
                required: true,
              },
            ]}
          >
            <DatePicker.RangePicker picker="month" />
          </Form.Item>
          <Form.Item
            label="日期年"
            name="rangePickerYear"
            rules={[
              {
                required: true,
              },
            ]}
          >
            <DatePicker.RangePicker picker="year" />
          </Form.Item>
        </Form.Item>
        <Form.Item label="切换不同的选择器" shouldUpdate>
          {/* 提供选择器,*切换不同类型的日期选择器,常用于日期筛选场合。 */}
          {(props) => {
            let pickerWithType = props.getFieldValue("selectType");
            let vdom = null;
            if (pickerWithType === "time") {
              vdom = <TimePicker />;
            } else if (pickerWithType === "date") {
              vdom = <DatePicker />;
            } else {
              vdom = <DatePicker picker={pickerWithType} />;
            }
            return (
              <Fragment>
                <Row>
                  <Col span={4}>
                    <Form.Item
                      label="选择类型"
                      name="selectType"
                      rules={[{ required: true }]}
                    >
                      <Select>
                        <Select.Option value="time">Time</Select.Option>
                        <Select.Option value="date">Date</Select.Option>
                        <Select.Option value="week">Week</Select.Option>
                        <Select.Option value="month">Month</Select.Option>
                        <Select.Option value="quarter">Quarter</Select.Option>
                        <Select.Option value="year">Year</Select.Option>
                      </Select>
                    </Form.Item>
                  </Col>
                  <Col span={12}>
                    <Form.Item
                      label="类型"
                      name="selectVal"
                      rules={[
                        {
                          required: true,
                          message: "必须输入纯文本.",
                        },
                      ]}
                    >
                      {vdom}
                    </Form.Item>
                  </Col>
                </Row>
              </Fragment>
            );
          }}
        </Form.Item>
        <Form.Item label="日期格式">
          {/* 使用 format 属性,可以自定义日期显示格式 */}
          <Form.Item
            rules={[{ required: true }]}
            label="YYYYMMDD"
            name="YYYYMMDD"
          >
            <DatePicker format="YYYY/MM/DD" />
          </Form.Item>
          <Form.Item
            rules={[{ required: true }]}
            label="DDMMYYYY"
            name="DDMMYYYY"
          >
            <DatePicker format="DD/MM/YYYY" />
          </Form.Item>
          <Form.Item rules={[{ required: true }]} label="DDMMYY" name="DDMMYY">
            <DatePicker format="DD/MM/YY" />
          </Form.Item>
          <Form.Item rules={[{ required: true }]} label="YYYYMM" name="YYYYMM">
            <DatePicker format="YYYY/MM" />
          </Form.Item>
          <Form.Item rules={[{ required: true }]} label="WEEK" name="weekMMDD">
            <DatePicker
              picker="week"
              format={(value) => {
                return `${moment(value)
                  .startOf("week")
                  .format("MM/DD")} ~ ${moment(value)
                  .endOf("week")
                  .format("MM/DD")}`;
              }}
            />
          </Form.Item>
          <Form.Item
            rules={[{ required: true }]}
            label="customFormatYYYYMMDD"
            name="customFormatYYYYMMDD"
          >
            <DatePicker
              format={(value) => {
                return `自定义format: ${value.format("YYYY/MM/DD")}`;
              }}
            />
          </Form.Item>
          <Form.Item
            rules={[{ required: true }]}
            label="rangePickerYYYYMMDD"
            name="rangePickerYYYYMMDD"
          >
            <DatePicker.RangePicker format="YYYY/MM/DD" />
          </Form.Item>
        </Form.Item>
        <Form.Item label="日期时间选择">
          {/* 增加选择时间功能,当 showTime 为一个对象时,其属性会传递给内建的 TimePicker。 */}
          <Form.Item
            rules={[{ required: true }]}
            label="datePickerShowTime"
            name="datePickerShowTime"
          >
            <DatePicker showTime />
          </Form.Item>
          <Form.Item
            rules={[{ required: true }]}
            label="rangePickerShowTime"
            name="rangePickerShowTime"
          >
            <DatePicker.RangePicker
              showTime={{ format: "HH:mm" }}
              format="YYYY-MM-DD HH:mm"
            ></DatePicker.RangePicker>
          </Form.Item>
        </Form.Item>
        <Form.Item label="禁用">
          {/* 选择框的不可用状态。你也可以通过数组单独禁用 RangePicker 的其中一项。 */}
          <Form.Item
            label="禁用日期"
            rules={[{ required: true }]}
            name="disabledDatePicker"
          >
            <DatePicker disabled />
          </Form.Item>
          <Form.Item
            label="禁用月份"
            rules={[{ required: true }]}
            name="disabledDatePickerMonth"
          >
            <DatePicker disabled picker="month" />
          </Form.Item>
          <Form.Item
            label="禁用日期区间"
            rules={[{ required: true }]}
            name="disabledDatePickerRangePicker"
          >
            <DatePicker.RangePicker disabled />
          </Form.Item>
          <Form.Item
            label="禁用部分日期区间"
            rules={[{ required: true }]}
            name="disabledDatePickerRangePicker1"
          >
            <DatePicker.RangePicker disabled={[false, true]} />
          </Form.Item>
        </Form.Item>
        <Form.Item label="不可选择日期和时间">
          {/* 可用 disabledDate 和 disabledTime 分别禁止选择部分日期和时间,其中 disabledTime 需要和 showTime 一起使用。 */}
          <Form.Item
            name="disableHourMinutesSecond"
            rules={[{ required: true }]}
            label="锁定时分秒"
          >
            <DatePicker
              format="YYYY-MM-DD HH:mm:ss"
              disabledDate={(current) => {
                //锁定日期
                return current && current < moment().endOf("day");
              }}
              disabledTime={(_, type) => {
                return {
                  disabledHours: () => {
                    // [0,24]=>去掉索引为4直接删除20位 锁上[0,1,2,3]小时
                    return range(0, 24).splice(4, 20);
                  },
                  disabledMinutes: () => {
                    // 锁上了30-60分钟
                    return range(30, 60);
                  },
                  disabledSeconds: () => {
                    // 锁上了55,56分钟
                    return [55, 56];
                  },
                };
              }}
              showTime
            />
          </Form.Item>
          <Form.Item
            name="disableMonth"
            label="禁用月份"
            rules={[{ required: true }]}
          >
            <DatePicker
              picker="month"
              disabledDate={(current) => {
                return current && current < moment().endOf("day");
              }}
            />
          </Form.Item>
          <Form.Item
            label="锁定日期"
            name="disabledDatePickerInner"
            rules={[{ required: true }]}
          >
            <DatePicker
              disabledDate={(current) => {
                return current && current < moment().endOf("day");
              }}
            />
          </Form.Item>
          <Form.Item
            name="disabledStartEnd"
            label="开始时间和结束时间不同锁定"
            rules={[{ required: true }]}
          >
            <DatePicker.RangePicker
              disabledDate={(current) => {
                return current && current < moment().endOf("day");
              }}
              disabledTime={(_, type) => {
                if (type === "start") {
                  return {
                    disabledHours: () => {
                      return range(0, 60).splice(4, 20);
                    },
                    disabledMinutes: () => {
                      return range(30, 60);
                    },
                    disabledSeconds: () => {
                      return [55, 56];
                    },
                  };
                } else {
                  return {
                    disabledHours: () => {
                      return range(0, 60).splice(20, 4);
                    },
                    disabledMinutes: () => {
                      return range(0, 31);
                    },
                    disabledSeconds: () => {
                      return [55, 56];
                    },
                  };
                }
              }}
              showTime={{
                hideDisabledOptions: true, //隐藏禁用选项
              }}
              format="YYYY-MM-DD HH:mm:ss"
            />
          </Form.Item>
        </Form.Item>
        <Form.Item name='notExceedSevenDay' label="选择不超过七天" rules={[{required:true}]}>
          {/* 如何用 onCalendarChange 和 disabledDate 来限制动态的日期区间选择。 */}
          <DatePicker.RangePicker
            disabledDate={(current) => {
              if (!dates || dates.length === 0) {
                return false;
              }
              const tooLate = dates[0] && current.diff(dates[0], "days") > 7;
              const tooEarly = dates[1] && dates[1].diff(current, "days") > 7;
              return tooEarly || tooLate;
            }}
            onCalendarChange={(val) => {
              console.log(111,val);
              setDates(val);
            }}
            onChange={(val) => {
              console.log(222,val);
              setValue(val);
            }}
            onOpenChange={(open) => {
              if (open) {
                setHackValue([]);
                setDates([]);
              } else {
                setHackValue(undefined);
              }
            }}
          />
        </Form.Item>
        <Form.Item label="预设范围">
          {/* 可以预设常用的日期范围以提高用户体验。 */}
          <Form.Item
            label="快捷键日期"
            name="shortcutKeyDate"
            rules={[{ required: true }]}
          >
            <DatePicker.RangePicker
              ranges={{
                今天: [moment(), moment()],
                这个月: [moment().startOf("month"), moment().endOf("month")],
              }}
            />
          </Form.Item>
          <Form.Item
            label="快捷键日期时间"
            name="shortcutKeyDateTime"
            rules={[{ required: true }]}
          >
            <DatePicker.RangePicker
              ranges={{
                今天: [moment(), moment()],
                这个月: [moment().startOf("month"), moment().endOf("month")],
              }}
              showTime
              format="YYYY/MM/DD HH:mm:ss"
            />
          </Form.Item>
        </Form.Item>
        <Form.Item label="额外的页脚">
          <Form.Item
            label="日期额外页脚"
            name="extralFooterDatePicker"
            rules={[{ required: true }]}
          >
            <DatePicker
              renderExtraFooter={() => {
                return <span>额外的页脚</span>;
              }}
            />
          </Form.Item>
          <Form.Item
            label="日期时间额外页脚"
            name="extralFooterDatePickerTime"
            rules={[{ required: true }]}
          >
            <DatePicker
              showTime
              renderExtraFooter={() => {
                return <span>额外的页脚</span>;
              }}
            />
          </Form.Item>
          <Form.Item
            label="日期区间额外页脚"
            name="extralFooterDatePickerRangePicker"
            rules={[{ required: true }]}
          >
            <DatePicker.RangePicker
              renderExtraFooter={() => {
                return <span>额外的页脚</span>;
              }}
            />
          </Form.Item>
          <Form.Item
            label="日期区间额外页脚"
            name="extralFooterDatePickerRangePickerTime"
            rules={[{ required: true }]}
          >
            <DatePicker.RangePicker
              showTime
              renderExtraFooter={() => {
                return <span>额外的页脚</span>;
              }}
            />
          </Form.Item>
          <Form.Item
            label="日期区间额外页脚"
            name="extralFooterDatePickerRangePickerMonth"
            rules={[{ required: true }]}
          >
            <DatePicker.RangePicker
              picker="month"
              renderExtraFooter={() => {
                return <span>额外的页脚</span>;
              }}
            />
          </Form.Item>
        </Form.Item>
        <Form.Item label="定制日期单元格">
          {/* 使用 dateRender 可以自定义日期单元格的内容和样式。 */}
          <Form.Item
            label="定制日期单元格"
            name="customDate"
            rules={[{ required: true }]}
          >
            <DatePicker
              dateRender={(current) => {
                const style = {};
                if (current.date() === 1) {
                  style.border = "1px solid #1890ff";
                  style.borderRadius = "50%";
                }
                return <div style={style}>{current.date()}</div>;
              }}
            />
          </Form.Item>
          <Form.Item
            label="定制日期单元格"
            name="customDateRangePicker"
            rules={[{ required: true }]}
          >
            <DatePicker.RangePicker
              dateRender={(current) => {
                const style = {};
                if (current.date() === 1) {
                  style.border = "1px solid red";
                  style.borderRadius = "50%";
                }
                return (
                  <div className="ant-picker-cell-inner" style={style}>
                    {current.date()}
                  </div>
                );
              }}
            />
          </Form.Item>
        </Form.Item>
        <Form.Item>
          <Button type="primary" htmlType="submit">
            提交
          </Button>
          <Button
            onClick={() => {
              form.resetFields();
            }}
          >
            重置
          </Button>
          <Button onClick={()=>{
            console.log(form.getFieldValue());
          }}>获取数据</Button>
        </Form.Item>
      </Form>
    </div>
  );
}
上一篇:antd vue表格分页序号重置问题


下一篇:ng-alain技术框架升级遇见的问题