我在项目中添加了onChange方法(React,TS,Mobx),但出现错误:Argument of type '{ [x: number]: any; }' is not assignable to parameter of type
我是TypeScript的新手,不确定为什么会这样。可能是什么问题?
(parameter) event: {
target: {
name: any;
value: any;
};
}
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;
最佳答案
您需要告诉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!");
}
关于javascript - React Typescript: '{ [x: number]: any; }'类型的参数无法分配给type类型的参数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/55729742/