React Typescript:'{ [x: number]: any; 类型的参数}' 不可分配给类型的参数

React Typescript: Argument of type '{ [x: number]: any; }' is not assignable to parameter of type

我在项目(React、TS、Mobx)中添加了 onChange 方法,但出现错误:Argument of type '{ [x: number]: any; }' is not assignable to parameter of type

我是 TypeScript 的新手,不确定为什么会这样。可能是什么问题?

(parameter) event: {
    target: {
        name: any;
        value: any;
    };
}

Argument of type '{ [x: number]: any; }' is not assignable to parameter of type 'IAddPlayerFormState | ((prevState: Readonly, props: Readonly) => IAddPlayerFormState | Pick | null) | Pick<...> | null'.

import React, { Component } from 'react';
import ViewStore from '../../../store/ViewStore';
import { TextField } from './../../../utils';

interface IAddPlayerFormProps {
  viewStore?: ViewStore; // Optional ViewStore
}

interface IAddPlayerFormState {
  playerName: string;
  isDisabled: boolean;
}

class AddPlayerForm extends Component<IAddPlayerFormProps, IAddPlayerFormState> {
  constructor(props: Readonly<IAddPlayerFormProps>) {
    super(props);

    this.state = {
      isDisabled: false,
      playerName: '',
    };
  }

  public onChange(event: { target: { name: any; value: any; }; }) {
    this.setState({ [event.target.name]: event.target.value });
    console.log('On Change!');
  }

  public handleSubmit = () => {
    console.log('On submit!');
  }

  public render() {
    const { isDisabled } = this.state;

    return (
      <form onSubmit={this.handleSubmit}>
        <TextField
          type="text"
          name="name"
          value={name}
          placeholder="Add player"
          onChange={this.onChange}
          disabled={isDisabled}
        />

        <input type="submit" />
      </form>
    );
  }
}

export default AddPlayerForm;

你的状态是这样的:

interface IAddPlayerFormState {
  playerName: string;
  isDisabled: boolean;
}

并且您正在调用 setState:

{any: any}

您只能更改值:playerName 和 isDisabled,不能更改。如果将函数签名重写为

public onChange(event: { target: { name: "playerName"|"isDisabled"; value: any; }; })

或更好

public onChange(event: { target: { name: keyof IAddPlayerFormState ; value: any; }; })

打字稿应该没问题。顺便说一句,这段代码将不起作用。更改输入名称 :)。我希望这个答案很清楚,如果不是我会编辑它。

您需要告诉 Typescript 您的对象将具有来自 IAddPlayerFormState 的一个或多个 属性,但不一定是所有属性。你可以这样做:

public onChange(event: { target: { name: any; value: any; }; }) {
  const newState = { [name]: value } as Pick<IAddPlayerFormState, keyof IAddPlayerFormState>;
  this.setState(newState);
  console.log("On Change!");
}

使用此语法为我消除了错误:

const myFunction = (e) => {
    return this.setState({...this.state, [e.target.id]: e.target.value});
}

你需要做的就是指定你想要的项目update/change

this.setState({value:value});
type ItemState = {
    value?: string;// The state I want to update
};

#你的情况是

this.setState({playerName : new_value});