gpt4 book ai didi

reactjs - 为 Antdesign Datepicker 转换为 Typescript

转载 作者:搜寻专家 更新时间:2023-10-30 21:09:54 25 4
gpt4 key购买 nike

我不知道如何在 handleDateChange 函数中注释 dateObj 参数

App.tsx

import { useState } from 'react';
import logo from './logo.svg';
import './App.css';
import { DatePicker } from 'antd'; // for css
import moment from 'moment';

const App = () => {
const [date, setDate] = useState(new Date())
const handleDateChange = (dateObj: Date, dateStr: string) => {
setDate(dateObj);
}
return (
<div className="App">
<DatePicker defaultValue={moment(date)} onChange={handleDateChange} />
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<p>
Edit <code>src/App.tsx</code> and save to reload.
</p>
<a
className="App-link"
href="https://reactjs.org"
target="_blank"
rel="noopener noreferrer"
>
Learn React
</a>
</header>
</div>
);
}

export default App;

这是 tslint 所说的 -

Type '(dateObj: Date, dateStr: string) => void' is not assignable to type '(date: Moment, dateString: string) => void'. Types of parameters 'dateObj' and 'date' are incompatible. Type 'Moment' is not assignable to type 'Date'. Property 'toDateString' is missing in type 'Moment'

但我不确定如何克服这个问题。

最佳答案

这是必需的。

 const [date, setDate] = useState(moment(new Date()));
const handleDateChange = (dateObj: moment.Moment, dateStr: string): void => {
setDate(dateObj);
}

然后

 <DatePicker defaultValue={date} onChange={handleDateChange} />

没有必要为 Moment 做一个单独的导入,因为 interface 和 NOT class 存在于 moment 命名空间,按照这个 reference

关于reactjs - 为 Antdesign Datepicker 转换为 Typescript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53994444/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com