gpt4 book ai didi

javascript - 错误: Argument of type '{ field1: Date; field2: Date; }' is not assignable to parameter of type 'IMyInterfaceState

转载 作者:行者123 更新时间:2023-12-02 21:18:36 24 4
gpt4 key购买 nike

我的接口(interface) (.tsx)如下:

export interface IMyInterfaceProps{
}

export interface IMyInterfaceState{
fields: {
ID:string,
Name:string,
field1: Date,
field2: Date,
date: Date
},
errors: {
Name: string,
}
}

我的类(class)(.tsx)是:

class MyClass extends Component<IMyInterfaceProps, IMyInterfaceState>{
form:any;
constructor(props:any){
super(props);
this.state = {
fields: {
ID:'',
Name:'',
field1: new Date(),
field2: new Date(),
date: new Date()
},
errors: {
Name: '',
}
};
}

change = (e:any) => {
this.setState({
[e.target.name]: e.target.value} as Pick<IMyInterfaceProps, keyof IMyInterfaceState>);
};

handleChange = (date: Date) => {
this.setState({
field1: date, //Here I'm getting this error
field2: date
});
};

render(){
<div>
<DatePicker id='field1' className="form-control" onChange={this.handleChange}
placeholderText="Select a date" ></DatePicker>
</div>
}
}

我的 package.json 依赖项是:

{
"name": "react-ds-poc",
"version": "0.1.0",
"private": true,
"dependencies": {
"@testing-library/jest-dom": "^4.2.4",
"@testing-library/react": "^9.3.2",
"@testing-library/user-event": "^7.1.2",
"@types/jest": "^24.0.0",
"@types/node": "^12.0.0",
"@types/react": "^16.9.26",
"@types/react-dom": "^16.9.0",
"bootstrap": "^4.4.1",
"css-loader": "^3.4.2",
"react": "^16.13.1",
"react-datepicker": "^2.14.1",
"react-dom": "^16.13.1",
"react-form-input-validation": "^2.0.3",
"react-scripts": "3.4.1",
"typescript": "^3.8.3"
}

我尝试了几种可解决此问题的解决方案 from here我可以解决我的 change 事件,但对于 handleChange 事件,我收到以下错误:

Argument of type '{ field1: Date; field2: Date; }' is not assignable to parameter of type 'IMyInterfaceState | ((prevState: Readonly, props: Readonly) => IMyInterfaceState | ... 1 more ... | null) | Pick<...> | null'.
Object literal may only specify known properties, and 'field1' does not exist in type 'IMyInterfaceState | ((prevState: Readonly, props: Readonly) => IMyInterfaceState | ... 1 more ... | null) | Pick<...>'.

请帮助我摆脱这个错误。

最佳答案

您当前仅使用 fields 属性的内容替换整个状态对象。您需要使用满足 IMyInterfaceState 约定的对象来设置状态。不完全确定,但你也许可以逃脱

this.setState({
fields: {
field1: date,
field2: date
}
});

但您可能还必须定义IDNamedate,也许还有errors.Name

关于javascript - 错误: Argument of type '{ field1: Date; field2: Date; }' is not assignable to parameter of type 'IMyInterfaceState,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60908032/

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