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

React DatePicker问题:未设置默认值却自动赋值的技术问询

React DatePicker 自动显示值问题排查与解决

核心原因及解决办法

  • 状态初始值未明确设为null:如果this.state.from_date初始为undefined,react-datepicker部分版本会自动将minDate/maxDate作为默认选中值(你的minDate设置为当天)。
    解决:组件初始化时将from_date明确设为null:

    constructor(props) {
      super(props);
      this.state = {
        from_date: null,
      };
    }
    
  • 自定义输入组件的默认值逻辑:检查ExampleCustomInput组件,若其内部在接收空值时自动填充当前日期,也会导致此问题。
    解决:修改自定义输入组件,确保当传入的value为null/undefined时,显示空内容而非自动填充日期。

修改后的示例代码

constructor(props) {
  super(props);
  this.state = {
    from_date: null,
  };
}

render() {
  return (
    <DatePicker
      dateFormat="dd/MM/yyyy"
      minDate={subDays(new Date(), 0)}
      wrapperClassName="date-picker"
      selected={this.state.from_date}
      onChange={(date: any) => {
        this.setState({
          from_date: date,
        });
      }}
      customInput={<ExampleCustomInput />}
      dayClassName={() => "example-datepicker-day-class"}
      popperClassName="example-datepicker-class"
      todayButton="TODAY"
    />
  );
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 02:10:25