Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
665 views
in Technique[技术] by (71.8m points)

reactjs - Typescript types for React checkbox events and handlers?

I'm building something like this React example in Typescript. The goal is to have a parent that has a state, and it creates several stateless child components that pass their clicks back to the parent.

Since the example is in Javascript I have no idea what the types of the input box events and the onChange handlers are...? I've tried several options like React.MouseEvent<HTMLInputElement>, but that's just guesswork...

Parent component create imageRows and pass the handler:

render() {
  <div>
    <ImageRow key={el.url} onChange={this.onChange}/>
  </div>
 }
 // what should the type of e be?
 onChange(e:any){
 }

And the ImageRow component

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>
}

EDIT

The similar question only shows the event type, not the handler type. When I change the event type:

onChange(e: React.FormEvent<HTMLInputElement>){
    console.log(e.target.value)
}

I get this error:

Property 'value' does not exist on type 'EventTarget'.
question from:https://stackoverflow.com/questions/45665188/typescript-types-for-react-checkbox-events-and-handlers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

When in doubt let it infer it for you by using an arrow in position e.g.

enter image description here

Answer

In your case e is React.ChangeEvent<HTMLInputElement>.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...