[英]TS2345: Argument of type 'Date | null' is not assignable to parameter of type 'string | Date | undefined'
I wanted to add a Date Picker to my form but i got this error Error: TS2345: Argument of type 'Date |我想在我的表单中添加一个日期选择器,但我收到了这个错误错误:TS2345:“日期”类型的参数 | null' is not assignable to parameter of type 'string | null' 不可分配给类型为“string |”的参数Date |日期 | undefined'.不明确的'。 Type 'null' is not assignable to type 'string |类型 'null' 不能分配给类型 'string | Date |日期 | undefined'.不明确的'。 Can anyone help me to solve it?谁能帮我解决它?
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>);}
DatePicker doesn't want null in the 'selected' prop and your birthDate useState is null, you can leave the default value for birthDate empty. DatePicker 不希望 null 在 'selected' 属性中并且您的birthDate useState 是 null,您可以将birthDate 的默认值留空。 And you should use const for React Hooks.你应该为 React Hooks 使用 const。
So:所以:
const [birthDate, setBirthDate] = useState<Date>();
It says that, you described your date state variable as can be null
or date
.它说,您将日期 state 变量描述为null
或date
。 However, it can also be undefined type.但是,它也可以是未定义的类型。 You can update your date state to this useState<Date|string|undefined>
.您可以将日期 state 更新为此useState<Date|string|undefined>
。
Alternatively, you can hover over to onChange
props of DatePicker to see the type of "date" param has.或者,您可以将 hover 切换到 DatePicker 的onChange
道具,以查看“日期”参数的类型。 Then you update your state type accordingly.然后相应地更新您的 state 类型。
const [birthDate, setBirthDate] = useState<Date | null | undefined>(null);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.