我的界面(.tsx)如下:

export interface IMyInterfaceProps{
}

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


我的班级(.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事件,我得到以下错误:


  类型'{字段1:日期; field2:日期; }'不可分配
  类型为'IMyInterfaceState的参数| ((prevState:
  只读,道具:只读)=>
  IMyInterfaceState | ... 1更多... | null)|选择 |空值'。
  对象文字只能指定已知属性,而“ field1”可以
  'IMyInterfaceState类型不存在((prevState:
  只读,道具:只读)=>
  IMyInterfaceState | ... 1更多... | null)|选择'。


请帮助我摆脱这个错误。

最佳答案

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

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


但是您可能还必须定义IDNamedate甚至errors.Name

关于javascript - 错误:类型为'{field1:Date;的参数; field2:日期; }”不可分配给“IMyInterfaceState”类型的参数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/60908032/

10-11 11:34