我想在表单中添加一个日期选择器,但出现了此错误错误:TS2345:类型为"Date|null"的参数不可分配给类型为"string|Date|undefined"的参数。类型"null"不可分配给类型"string|Date|undefined"export class Form extends React.Component<FormProps, {
fname: string | undefined;
lname: string | undefined;
birthDate: Date | undefined;
}> {
constructor(props: FormProps) {
super(props);
this.state = {
fname: undefined,
lname: undefined,
birthDate: undefined,
};
}
function testField(value: string | undefined | Date, set: React.Dispatch<React.SetStateAction<string | undefined>>): boolean {
if(value === undefined) {
set('');
return false;
}
if(value === '') {
return false;
}
return true;
}
let [fname, setfname] = useState<string | undefined>(undefined);
let [lsname, setlname] = useState<string | undefined>(undefined);
let [birthDate, setBirthDate] = useState<Date | null>(null);
const testNext = () => {
let success = true;
success = testField(fname, setFname) && success;
success = testField(lname, setlname) && success;
success = testField(birthDate, setBirthDate) && success;
return (<Fragment>
<div className="content__form">
<div className="formcolcontainer">
<div className="formcol">
<Input onChange={setFname} name="Fname" error={Fname=== ''}/>
<Input onChange={setlname} name="lname" error={lname=== ''}/>
</div>
<div className="formcol">
<DatePicker
id='BirthDate'
selected={birthDate}
onChange={(date) => setBirthDate(date)}
placeholderText="Birth Date"
/>
</div>
</div>
</div>
</Fragment>);}
它说,您将日期状态变量描述为null
或date
。但是,它也可以是未定义的类型。您可以将您的日期状态更新为此useState<Date|string|undefined>
。
或者,您可以将鼠标悬停在DatePicker的onChange
道具上,以查看";日期";param有。然后相应地更新您的状态类型。
const [birthDate, setBirthDate] = useState<Date | null | undefined>(null);
DatePicker不希望在"selected"道具中为null,并且您的birthDate useState为null,您可以将birthDate的默认值保留为空。您应该使用const作为React Hooks。
因此:
const [birthDate, setBirthDate] = useState<Date>();