React Typescript:类型'{[x:number]的参数:任意; }'不能分配给类型的参数 [英] 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
I added onChange method in my project(React, TS, Mobx), but I am getting an error: Argument of type '{ [x: number]: any; }' is not assignable to parameter of type
我是TypeScript的新手,不确定为什么会这样.可能是什么问题?
I am new to TypeScript and not sure why it's happening. What can be the problem?
(parameter) event: {
target: {
name: any;
value: any;
};
}
'{[x:number]类型的参数:任意; }'不可分配给 'IAddPlayerFormState类型的参数| ((prevState: 只读,道具:只读) => IAddPlayerFormState |选择| null)|选择< ...> |空".
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;
推荐答案
您需要告诉Typescript您的对象将具有IAddPlayerFormState的一个或多个属性,但不一定具有所有属性.您可以这样做:
You need to tell Typescript that your object will have one or more property from IAddPlayerFormState, but not necessarily all properties. You can do it like this:
public onChange(event: { target: { name: any; value: any; }; }) {
const newState = { [name]: value } as Pick<IAddPlayerFormState, keyof IAddPlayerFormState>;
this.setState(newState);
console.log("On Change!");
}
这篇关于React Typescript:类型'{[x:number]的参数:任意; }'不能分配给类型的参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!