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

Formik Material UI Keyboard Date Picker 传入Date初始值不默认展示如何实现

问题根因

你当前在Formik的initialValues中直接给date字段传入了new Date(),KeyboardDatePicker组件会默认读取这个值渲染到输入框,因此会默认显示当前日期。

方案1:无强制初始Date值要求(最推荐)

如果业务逻辑没有要求字段初始必须持有Date类型值,直接把初始值改为null即可,初始状态输入框会自动为空,用户操作后Formik会自动将值更新为Date类型:

<Formik
    initialValues={{ date: null }}
>
    {/* 其余代码不变 */}
</Formik>

方案2:必须保留Date类型初始值

如果业务要求字段初始就有Date默认值(比如用户未选择时提交默认传当前日期),可以在DatePicker组件内结合Formik的touched状态控制显示逻辑,修改DatePickerInput组件代码如下:

import React from 'react';
import { Field, useField } from 'formik';
import { KeyboardDatePicker } from 'formik-material-ui-pickers';
import { Grid }  from '@material-ui/core';

export interface DatePickerInputProps {
    sm: any,
    name: string,
    label: string,
    required?: boolean,
    disabled?: boolean,     
    disableFuture?: boolean,
    disablePast?: boolean,
    minDate?: Date,
    maxDate?: Date
}

export default function DatePickerInput( props: DatePickerInputProps ) {  
    const [ field, meta, helpers ] = useField(props.name);
    const errorText = meta.error;
    const showErrorText = !!meta.value ? !!meta.touched && !!errorText : !!errorText;
    
    return (
        <Grid item sm={props.sm || 12}>            
            <Field
                autoOk                                                              
                component={KeyboardDatePicker}                              
                name={props.name}
                label={props.label}
                disabled={props.disabled}
                required={props.required}
                error={showErrorText}
                helperText={showErrorText ? errorText : null}   
                fullWidth
                format='MM/dd/yyyy'                
                inputVariant='filled'               
                InputLabelProps={{
                    // 只有有值或者用户操作过之后才让标签上浮
                    shrink: meta.touched || !!meta.value
                }}
                // 控制显示值:用户未操作时显示空
                value={meta.touched ? field.value : null}
                // 用户选值后标记字段为已操作,同时更新值
                onChange={(date) => {
                  helpers.setValue(date);
                  helpers.setTouched(true);
                }}                                         
                disableFuture={props.disableFuture}
                disablePast={props.disablePast}
                minDate={props.minDate}
                maxDate={props.maxDate}            
            />                                  
        </Grid>
    )
}

如果需要保留提交时默认传当前日期的逻辑,在Formik的onSubmit回调中加一层判断即可:

onSubmit: (values) => {
  const submitValues = {
    ...values,
    date: values.date || new Date()
  }
  // 后续提交逻辑
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.10 05:33:03