Typescript input onchange event.target.value

后端 未结 11 917
隐瞒了意图╮
隐瞒了意图╮ 2020-11-28 21:25

In my react and typescript app, I use: onChange={(e) => data.motto = (e.target as any).value}.

How do I correctly define the typings for the class, s

11条回答
  •  Happy的楠姐
    2020-11-28 22:01

    The target you tried to add in InputProps is not the same target you wanted which is in React.FormEvent

    So, the solution I could come up with was, extending the event related types to add your target type, as:

    interface MyEventTarget extends EventTarget {
        value: string
    }
    
    interface MyFormEvent extends React.FormEvent {
        target: MyEventTarget
    }
    
    interface InputProps extends React.HTMLProps {
        onChange?: React.EventHandler>;
    }
    

    Once you have those classes, you can use your input component as

     alert(e.target.value)} />
    

    without compile errors. In fact, you can also use the first two interfaces above for your other components.

提交回复
热议问题