我在跟踪离子反应教程。我创建了教程页面,并试图向其中添加一个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;
我使用的数据报警器来自这里,我使用了页面中的第一个示例:
() => {
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 | );
有什么问题吗?
发布于 2019-12-27 09:54:09
来自onChange
的react-datepicker
回调看起来像这
onChange(date: Date | null, event: React.SyntheticEvent<any> | undefined): void;
所以date
有可能是null
。你在这里有两个选择:
1.)接受useState
钩中的可空日期状态:
const [startDate, setStartDate] = useState<Date | null>(new Date());
2.)只有当setStartDate
不是null时,才调用date
:
<DatePicker selected={startDate} onChange={date => date && setStartDate(date)} />
发布于 2021-06-02 08:54:40
2021年同一期更新
<DatePicker selected={startDate} onChange={(date: Date | null) => setStartDate(date)} />
干这活
发布于 2021-07-03 14:54:03
我知道我入党迟到了,我刚刚拿到了DatePicker。以下是工作守则:
const [startDate, setStartDate] = useState<Date>(new Date());
<DatePicker
selected={startDate}
onChange={(date: Date) => setStartDate(date!)}
/>
https://stackoverflow.com/questions/59497548
复制相似问题