You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

KendoReact DatePicker嵌套Form时手动输入年份仅一位数的解决方法

解决Kendo React DatePicker嵌套Form时无法输入4位年份的问题

问题根源

当DatePicker未通过Form的Field组件与表单字段绑定,仅靠id关联时,Form的内部值同步逻辑会错误解析输入的年份字符串,导致仅保留第一位有效数字,出现输入2025变成0002的异常。

解决方案

通过Form的Field组件将DatePicker与表单字段绑定,让Form正确识别DatePicker的值类型(Date对象),而非直接解析输入的字符串。同时显式指定parseFormat与format一致,确保输入解析逻辑匹配显示格式。

修改后的代码示例

  1. 父组件(Form部分):
import { Form, FormElement, Field } from "@progress/kendo-react-form";

// 假设props包含tasks数组
<Form initialValues={{ tasks: props.tasks }}>
 <FormElement>
  {props.tasks.map((_, index) => (
    <Field 
      key={index}
      name={`tasks[${index}].dueDate`}
      render={(fieldProps) => <DueDate index={index} fieldProps={fieldProps} />}
    />
  ))}
 </FormElement>
</Form>
  1. DueDate组件:
import { DatePicker } from "@progress/kendo-react-dateinputs";
import { Label } from "@progress/kendo-react-labels";

export interface DueDateProps {
  index: number;
  fieldProps: any; // 可根据Kendo官方类型定义替换为更精确的`FieldProps<Date>`
}

const DueDate = ({ index, fieldProps }: DueDateProps): JSX.Element => {
 return (
  <div>
   <Label className="k-form-label" htmlFor={`tasks[${index}].dueDate`}>Date Field</Label>
   <DatePicker 
     id={`tasks[${index}].dueDate`}
     format="MM/dd/yyyy"
     parseFormat="MM/dd/yyyy" // 显式指定输入解析格式
     autoSwitchKeys={["tab"]}
     placeholder="Select date"
     {...fieldProps} // 绑定Form Field的value、onChange等核心属性
   />
  </div>
 );
}

额外注意事项

  • 确保Form的initialValues中对应字段的初始值为Date类型或undefined,避免初始值类型错误引发的解析异常。
  • 若问题仍存在,可尝试移除autoSwitchKeys配置,验证是否为自动切换逻辑干扰了年份输入流程。

内容的提问来源于stack exchange,提问作者Anna P

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.12 10:25:08