我正在关注 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 | );
问题是什么?
最佳答案
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)} />
关于reactjs - 'Date | null' 类型的参数不能分配给 'SetStateAction<Date>' 类型的参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59497548/