'Date | null' 类型的参数不可分配给 'SetStateAction<Date>' 类型的参数

Argument of type 'Date | null' is not assignable to parameter of type 'SetStateAction<Date>'

我正在关注Ionic tutorial for react。 我创建了教程页面,并尝试向其中添加日期选择器元素。这是我现在的页面:

import { IonContent, IonHeader, IonPage, IonTitle, IonToolbar } from '@ionic/react';
import React, { useState } from 'react';
import DatePicker from 'react-datepicker'
import "react-datepicker/dist/react-datepicker.css";

const Home: React.FC = () => {
  const [startDate, setStartDate] = useState(new Date());
  return (
    <IonPage>
      <IonHeader>
        <IonToolbar>
          <IonTitle>Ionic Blank</IonTitle>
        </IonToolbar>
      </IonHeader>
      <IonContent className="ion-padding">
        The world is your oyster 14.
        <p>
          If you get lost, the{' '}
          <a target="_blank" rel="noopener noreferrer" href="https://ionicframework.com/docs/">
            docs
          </a>{' '}
          will be your guide.
        </p>
        <DatePicker selected={startDate} onChange={date => setStartDate(date)} />
      </IonContent>
    </IonPage>
  );
};

export default Home;

我使用的日期选择器来自 here,我在页面中使用了第一个示例:

() => {
  const [startDate, setStartDate] = useState(new Date());
  return (
    <DatePicker selected={startDate} onChange={date => setStartDate(date)} />
  );
};

但是,我收到以下错误:

[react-scripts] Argument of type 'Date | null' is not assignable to parameter of type 'SetStateAction<Date>'.
[react-scripts]   Type 'null' is not assignable to type 'SetStateAction<Date>'.  TS2345
[react-scripts]     22 |           will be your guide.
[react-scripts]     23 |         </p>
[react-scripts]   > 24 |         <DatePicker selected={startDate} onChange={date => setStartDate(date)} />
[react-scripts]        |                                                                         ^
[react-scripts]     25 |       </IonContent>
[react-scripts]     26 |     </IonPage>
[react-scripts]     27 |   );

有什么问题?

来自 react-datepickeronChange 回调看起来像 this:

onChange(date: Date | null, event: React.SyntheticEvent<any> | undefined): void;

所以 date 可能是 null。您在这里有两个选择:


1.) 在 useState 钩子中接受可为空的日期状态:

const [startDate, setStartDate] = useState<Date | null>(new Date());

2.) 仅在 date 不为 null 时调用 setStartDate

<DatePicker selected={startDate} onChange={date => date && setStartDate(date)} />

2021 年同一问题的更新

<DatePicker selected={startDate} onChange={(date: Date | null) => setStartDate(date)} />

做这份工作

我知道我来晚了,我刚刚让 DatePicker 开始工作。 以下是工作代码:

const [startDate, setStartDate] = useState<Date>(new Date());
<DatePicker
   selected={startDate}
   onChange={(date: Date) => setStartDate(date!)}
/>

这对我有用:

() => {
  const [startDate, setStartDate] = useState<Date|null>(new Date());
  return (
    <DatePicker selected={startDate} onChange={(date: Date | null) => setStartDate(date)} />
  );
};