reactjs - 我无法在打字稿中使用动态键名设置状态
问题描述
我定义了 React 组件的状态接口如下。
interface IState {
email: string,
password: string,
errors: object
}
在文本输入更改事件中,我尝试使用如下动态键设置状态。
handleInputChange(e: React.ChangeEvent<HTMLInputElement>) {
this.setState({
[e.target.name]: e.target.value
});
}
但是 VSCode 向我显示了这个错误
Argument of type '{ [x: string]: string; }' is not assignable to parameter of type 'IState | ((prevState: Readonly<IState>, props: Readonly<{}>) => IState | Pick<IState, "email" | "password" | "errors"> | null) | Pick<IState, "email" | "password" | "errors"> | null'.
Type '{ [x: string]: string; }' is missing the following properties from type 'Pick<IState, "email" | "password" | "errors">': email, password, errorsts(2345)
任何的建议都受欢迎。
解决方案
问题是它e.target.name
应该是 key ofIState
并且e.target.value
应该是 key in 的相对类型IState
,要修复它,您可以手动转换类型,例如
this.setState({
[e.target.name]: e.target.value
} as Pick<IState, keyof IState>);
但它禁用了这个函数的打字稿,你也可以将它转换为任何类型,但它是不安全的。
看起来这个答案对你也有帮助
最好的选择是使用ReduxForm
推荐阅读
- linkedin - 如何使用 netsuite 的 share Api 在 Linkedin 中发布内容
- highcharts - 高图。在导出图表标签被裁剪
- c# - MIME 参数值应该用双引号括起来
- android - 如何使用 kotlin 在我的 Tablayout 中显示这两个选项卡?
- linux - 如何在 suse linux Enterprise 11 sp 4 上安装 oci8
- python - 在 Python 中从数组中获取特定元素
- apache-spark - Spark DataFrames 是否曾经隐式缓存过?
- apache - 所有对 Restful webservice 的 post-requests 都提供 Http 415
- python - Flask - 获取用户输入并将其传递给后端
- c# - 在 Flurl http get 请求中处理双重编码