我正在关注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 | );
怎么了?
onChange
中的react-datepicker
回调看起来像this:
onChange(date: Date | null, event: React.SyntheticEvent<any> | undefined): void;
因此date
可能是null
。您在这里有两个选择:
1。)在useState
挂钩中接受可为空的日期状态:
const [startDate, setStartDate] = useState<Date | null>(new Date());
2。)仅在setStartDate
不为空时调用date
:
<DatePicker selected={startDate} onChange={date => date && setStartDate(date)} />