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

如何让Antd Datepicker默认展开至指定有效年份且无选中值?

解决方案:Antd Datepicker 默认展开至17年前年份且无默认选中值

要实现需求,只需调整两处关键配置,同时统一日期库使用:

  • 移除Form.Item的initialValue,避免设置默认选中值
  • 给DatePicker添加defaultOpenValue属性,指定打开时默认定位到当前日期减17年的日期,该属性仅控制选择器展开时的定位,不会设置为选中值

修改后的完整代码

<Form.Item
    label="Birthdate"
    name="birthdate"
>
    <DatePicker
        allowClear={false}
        placeholder=""
        onChange={(date, dateString) => formik.setFieldValue('birthdate', dateString)}
        value={formik.values.birthdate ? moment(formik.values.birthdate, 'MM/DD/YYYY') : null}
        size="large"
        style={{ width: '100%' }}
        format="MM/DD/YYYY"
        disabledDate={(current) =>
            current && current > moment().subtract(17, 'years')
        }
        defaultOpenValue={moment().subtract(17, 'years')}
    />
</Form.Item>

额外提示

你代码中同时混用了dayjs和moment两个日期库,建议统一使用其中一个,避免潜在的兼容性问题。如果项目依赖dayjs,只需将所有moment替换为dayjs即可,例如:

defaultOpenValue={dayjs().subtract(17, 'years')}
value={formik.values.birthdate ? dayjs(formik.values.birthdate, 'MM/DD/YYYY') : null}
disabledDate={(current) =>
    current && current > dayjs().subtract(17, 'years')
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 04:53:20