属性“名称”在HTMLInputElement类型上不存在?

const handleOnChange = (e: React.SyntheticEvent<HTMLInputElement>): void => {
    console.log(e.name);
  }

<input name="aa" onChange={handleOnChange} />

Why HTMLInputElement doesn't have name attribute in react?

评论
  • FBI
    FBI 回复

    The correct type for the change event object is: ChangeEvent<HTMLInputElement>.

    Although the e.name isn't exists, the correct way to get the element's name attribute is e.target.name where the target object in the event is be the input element itself, and you need the name attribute from that.

    So your handleOnChange method would look like:

    const handleOnChange = (e: ChangeEvent<HTMLInputElement>): void => {
        console.log(e.target.name);
    }
    

    要么:

    const handleOnChange: ChangeEventHandler<HTMLInputElement> = (e) => {
        console.log(e.target.name);
    }
    

    In this case you define the type for the handleOnChange variable, and you assign the arrow function to that, so TypeScript will infer the type for e accordingly.