描述
React 编写的页面中有很多表单填写的 input,原本都是用如下的内容来编写:
state = {
mobile: '',
smsCaptcha: '',
passWord: '',
otherState: 0,
}
handleInput = (key, value) => {
this.setState({
[key]: value
})
}
render() {
return (
<div>
<input
type='tel'
maxLength={11}
value={mobile}
placeholder='请输入手机号'
onChange={event => this.handleInputChange('mobile', event.target.value) }
/>
<input
type='number'
value={smsCaptcha}
placeholder='请输短信验证码'
onChange={event => this.handleInputChange('smsCaptcha', event.target.value) }
/>
...
</div>
)
}
现在需要将原始的项目使用 ts 重写
首先 state 的 interface 各个属性中有存在不是 string 的类型:
interface IState {
mobile: string
smsCaptcha: string
passWord: string
otherState: number
}
现在需要给 handleInput 方法加上 typescript 验证:
handleInput = (key: string, value: string) => {
this.setState({
[key]: value
})
}
上面的写法会导致错误:
Argument of type '{ [x: string]: string; }' is not assignable to parameter of type ...
即便我想办法获取了当前 state 的 interface 中所有可以是 string 的类型 也不行:
handleInput = (key: 'mobile' | 'smsCaptcha' | 'passWord', value: string) => {
this.setState({
[key]: value
})
}
有什么比较好的方案么?
四处用 any 的话引入 ts 就没有意义了。ts 这里已经提醒了你有潜在的问题,应该对输入的数据进行处理,提供一种思路供参考。