“日期|类型”的参数“ null”不可分配给“ SetStateAction <Date>”类型的参数

时间:2019-12-27 07:39:22

标签: reactjs typescript ionic-framework react-datepicker

我正在关注Ionic tutorial for react。 我创建了教程页面,并试图向其中添加一个datepicker元素。这是我的当前页面:

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 |   );

出什么问题了?

4 个答案:

答案 0 :(得分:2)

2021 年更新同一问题

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

做这份工作

答案 1 :(得分:0)

来自onChange的{​​{1}}回调类似于this

react-datepicker

因此onChange(date: Date | null, event: React.SyntheticEvent<any> | undefined): void; 可能是date。您在这里有两个选择:


1。)在null钩中接受可为空的日期状态:

useState

2。)仅在const [startDate, setStartDate] = useState<Date | null>(new Date()); 不为空时调用setStartDate

date

答案 2 :(得分:0)

我知道我参加聚会迟到了,我刚刚让 DatePicker 工作。 以下是工作代码:

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

答案 3 :(得分:0)

这对我有用:

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