我有被定义为接口的som react状态,并且具有特定的所有命名键…
我在下面尝试了一种解决方案,该解决方案应在技术上基于状态键起作用,但仍然会给我错误
{ [x: string]: string; }' provides no match for the signature ...
做这个的最好方式是什么…
interface State {
responses: string,
comments: string,
}
state = {
responses: '',
comments: '',
};
handleChange = (e: React.ChangeEvent<HTMLInputElement>, value: string): void => {
const key = e.currentTarget.name;
Object.keys(this.state).forEach(k => {
if (k === key) this.setState({ [e.currentTarget.name]: value });
})
}
的返回类型Object.keys()
是通用的,string[]
而不是对象键的并集的数组,因此在此处推断正确的类型可能很棘手。而且,根据我的经验,当发布较新版本的TypeScript或程序包类型定义时,智能解决方案往往会崩溃,因此在这种情况下,我将帮助TypeScript在以下参数上签名setState
:
handleChange = (e: React.ChangeEvent<HTMLInputElement>, value: string): void => {
const key = e.currentTarget.name;
if (Object.keys(this.state).includes(key)) {
this.setState({[key]: value } as Pick<State, keyof State>);
}
}