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?
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?
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'sname
attribute ise.target.name
where thetarget
object in the event is be the input element itself, and you need thename
attribute from that.So your
handleOnChange
method would look like:要么:
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 fore
accordingly.