Typescript input onchange event.target.value

后端 未结 11 845
隐瞒了意图╮
隐瞒了意图╮ 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条回答
  • 2020-11-28 21:48

    An alternative that has not been mentioned yet is to type the onChange function instead of the props that it receives. Using React.ChangeEventHandler:

    const stateChange: React.ChangeEventHandler<HTMLInputElement> = (event) => {
        console.log(event.target.value);
    };
    
    0 讨论(0)
  • 2020-11-28 21:51

    Generally event handlers should use e.currentTarget.value, e.g.:

    onChange = (e: React.FormEvent<HTMLInputElement>) => {
        const newValue = e.currentTarget.value;
    }
    

    You can read why it so here (Revert "Make SyntheticEvent.target generic, not SyntheticEvent.currentTarget.").

    UPD: As mentioned by @roger-gusmao ChangeEvent more suitable for typing form events.

    onChange = (e: React.ChangeEvent<HTMLInputElement>)=> {
       const newValue = e.target.value;
    }
    
    0 讨论(0)
  • 2020-11-28 21:52

    Here is a way with ES6 object destructuring, tested with TS 3.3.
    This example is for a text input.

    name: string = '';
    
    private updateName({ target }: { target: HTMLInputElement }) {
        this.name = target.value;
    }
    
    0 讨论(0)
  • 2020-11-28 21:52
      function handle_change(
        evt: React.ChangeEvent<HTMLInputElement>
      ): string {
        evt.persist(); // This is needed so you can actually get the currentTarget
        const inputValue = evt.currentTarget.value;
    
        return inputValue
      }
    

    And make sure you have "lib": ["dom"] in your tsconfig.

    0 讨论(0)
  • 2020-11-28 21:53

    This is when you're working with a FileList Object:

    onChange={(event: React.ChangeEvent<HTMLInputElement>): void => {
      const fileListObj: FileList | null = event.target.files;
      if (Object.keys(fileListObj as Object).length > 3) {
        alert('Only three images pleaseeeee :)');
      } else {
        // Do something
      }
    
      return;
    }}
    
    0 讨论(0)
  • 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<T> extends React.FormEvent<T> {
        target: MyEventTarget
    }
    
    interface InputProps extends React.HTMLProps<Input> {
        onChange?: React.EventHandler<MyFormEvent<Input>>;
    }
    

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

    <Input onChange={e => alert(e.target.value)} />
    

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

    0 讨论(0)
提交回复
热议问题