使用组件回调的React Typesscript



如何使用回调方法?

这是组件的调用:

//This is the Parent Component
const [selectedDateState, setSelectedDateState] = React.useState();
...
<DateSelection initDate={new Date()} label={"Pick a date"} onValueChange={setSelectedDateState}/>
{/*^^^^^^^^^^^^ Error */}

我收到错误消息:

TS2322: Type 'Dispatch<SetStateAction<undefined>>' 
is not assignable to type '(newDate: Date) => void'.   
Types of parameters 'value' and 'newDate' are incompatible.     
Type 'Date' is not assignable to type 'SetStateAction<undefined>'.       
Type 'Date' provides no match for the signature '(prevState: undefined): undefined'.

这就是组件,一个简单的日期选择器。当我叫它的时候,我会传递今天的日期和标签。如果日期已更改,则应将日期设置为父页中的状态。

日期选择.tsx

import 'date-fns';
import React, {useEffect} from 'react';
import Grid from '@material-ui/core/Grid';
import DateFnsUtils from '@date-io/date-fns';
import {
MuiPickersUtilsProvider,
KeyboardDatePicker,
} from '@material-ui/pickers';
type ChildProps = {
initDate: Date, 
label: string,
onValueChange: (newDate: Date) => void;
}
export default function DateSelection({initDate, label, onValueChange}: ChildProps) {
// The first commit of Material-UI
const [selectedDate, setSelectedDate] = React.useState<Date>();
const handleDateChange = (date: Date | null) => {
if (date) {
setSelectedDate(date);
onValueChange(date);
}
};
useEffect(() => {
setSelectedDate(initDate);
}, [])
return (
<MuiPickersUtilsProvider utils={DateFnsUtils}>
<Grid container justify="space-around">
<KeyboardDatePicker
margin="normal"
id="date-picker-dialog"
label= {label}
format="dd.MM.yyyy"
value={selectedDate}
onChange={handleDateChange}
KeyboardButtonProps={{
'aria-label': 'change date',
}}
/>
</Grid>
</MuiPickersUtilsProvider>
);
}

这是因为React.useState中的setSelectedDateState具有类型签名:Dispatch<SetStateAction<undefined>>,并且您已将onValueChange的类型定义为(newDate: Date) => void

因此,您可以将onValueChange的类型更改为Dispatch<SetStateAction<Date>>,其中DispatchSetStateAction来自React。。。

import * as React from "react";
type DateSelectionProps = {
...
onValueChange: React.Dispatch<React.SetStateAction<Date>>;
}

或者将组件更改为以下内容,以便匹配为onValueChange:定义的类型签名

const [selectedDateState, setSelectedDateState] = React.useState<Date>();
...
<DateSelection initDate={new Date()} label={"Pick a date"} onValueChange={(date) => setSelectedDateState(date)}/>

对不起

我找到了一个解决方案。我必须在父组件中使用useCallback而不是useState!

const handleSelectedDate = useCallback((e)=>{
console.log(e);
setSelectedDateState( e );
},[]);
...
<DateSelection initDate={new Date()} label={"Pick a date"} onValueChange={ handleSelectedDate }/>

最新更新