React + Typescript:如何输入 event.target.name 来声明? [英] React + Typescript: How to type event.target.name to state?
问题描述
我有一些反应状态被定义为一个接口并且具有特定的所有命名键...
I have som react state that was defined as an interface and has specificall named keys...
我尝试了下面的解决方案,该解决方案应该基于状态键在技术上有效,但它仍然给我错误
I tried a solution below that should technically work based on the state keys, but it still gives me the error
{ [x: string]: string; }' provides no match for the signature ...
最好的方法是什么...
What is the best way to do this...
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
的参数进行签名:
The return type of Object.keys()
is the generic string[]
rather than an array of the union of the keys of the object, so it's probably tricky to infer the correct types here. Moreover, in my experience, smart solutions have a tendency to break when newer versions of TypeScript or package type definitions are released, so in this case I would just help TypeScript with a signature on to the argument of 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>);
}
}
这篇关于React + Typescript:如何输入 event.target.name 来声明?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!