我收到此错误
错误:(17,35)TS2339:类型'EventTarget&Element'上不存在'checked'属性。
但这绝对是不可能的错误,因为React文档说checked
确实存在于复选框(https://reactjs.org/docs/forms.html#handling-multiple-inputs)的target
这是我的代码。怎么了,TS炸毁了?
// I specify a type for event. It must have `checked` property.
onToggle = (ev: React.ChangeEvent) => {
console.log('[ev]', ev.target.checked); // <= TS throws here
}
render() {
return (
<div>
<input type="checkbox" name="switch" id="switch" onChange={ev => this.onToggle(ev)} checked={this.state.on}/>
</div>
)
}
答案 0 :(得分:3)
这是一个修复程序。您必须指定ChangeEvent
onToggle = (ev: React.ChangeEvent<HTMLInputElement>) => {
// onToggle = (ev: React.ChangeEvent) => {
console.log('[ev]', ev.target.checked); // <= TS throws here
}
render() {
return (
<div>
<input type="checkbox" name="switch" id="switch" onChange={ev => this.onToggle(ev)} checked={this.state.on}/>
</div>
)
}