【发布时间】:2018-01-21 17:47:47
【问题描述】:
我正在 Typescript 中构建类似 this React example 的东西。目标是让父级有状态,并创建几个无状态的子组件,将它们的点击传回父级。
由于示例是用 Javascript 编写的,我不知道输入框事件和 onChange 处理程序的类型是什么......?我已经尝试了几个选项,比如React.MouseEvent<HTMLInputElement>,但这只是猜测......
父组件 创建 imageRows 并传递处理程序:
render() {
<div>
<ImageRow key={el.url} onChange={this.onChange}/>
</div>
}
// what should the type of e be?
onChange(e:any){
}
还有 ImageRow 组件
export interface ImageRowProps {
genre: Array<number>
url: string
onChange : any // what is the type of the callback function?
}
export class ImageRow extends React.Component<ImageRowProps> {
render() {
return <div className="imagerow">
<input type="checkbox" key={index} onChange={this.props.onChange} defaultChecked={(num == 1)}/>
</div>
}
编辑
类似的问题只显示事件类型,而不是处理程序类型。当我更改事件类型时:
onChange(e: React.FormEvent<HTMLInputElement>){
console.log(e.target.value)
}
我收到此错误:
Property 'value' does not exist on type 'EventTarget'.
【问题讨论】:
-
谢谢...显示事件类型
onChange(e: React.FormEvent<HTMLInputElement>)。但是在props中还是找不到change handler的类型... -
似乎您正在使用过时的定义文件进行反应?对于较新的版本,它应该类似于
Property 'value' does not exist on type 'EventTarget & HTMLInputElement'。 -
嗯版本好像被锁定了?如果我更新它仍然是
@types/react": "^15.6.1但在 npm 上它说最新版本是16.0.2 -
也许你的反应也没有更新?无论如何,如果您有旧版本的定义,请查看标记为重复的问题中的第二个答案。我很确定它会解决你的问题,如果它对你有用,请更新,所以我会关闭这个重复的
标签: reactjs typescript