我的问题与this one非常相似,但是那里没有任何答案可以解决我的问题。我有一个简单的表单,带有命名输入,它们对应于React组件状态中的值。该组件具有一个更改处理程序,该更改处理程序在输入值更改时会相应地更新状态:
interface State {
name: string,
email: string,
address: string,
zip: string,
}
class Form extends React.Component<Props, State> {
state = {
name:'',
email: '',
address: '',
zip: '',
};
handleChange = ({ target }: React.ChangeEvent<HTMLInputElement>) => {
const { name, value } = target;
this.setState({ [name]: value });
}
render() {
...
}
}
但是,打字稿给我以下错误:
Type '{ [x: string]: string; }' is missing the following properties from type 'Pick<State, "name" | "email" | "address" | "zip">': name, email, address, zip.
如上所述,我尝试了以下解决方案:
handleChange = ({ target }: React.ChangeEvent<HTMLInputElement>): void => {
const { name, value } = target;
if (Object.keys(this.state).indexOf(name) > -1) {
this.setState({ [name]: value } as Pick<State, keyof State>);
}
}
handleChange = ({ target }: React.ChangeEvent<HTMLInputElement>): void => {
const { name, value } = target;
this.setState({ [name]: value } as { [K in keyof State]: State[K] });
}
,但两种解决方案均无效。还有另一种输入名称和值的方法吗?