简体   繁体   中英

TypeScript correct way to type onChange handler

I have a simple controlled input that looks like the following:

<textarea
  name="description"
  onChange={updateEdit}
  value={edit}
  placeholder={edit}
/>

my updateEdit handler

const updateEdit = (evt: React.ChangeEventHandler<HTMLTextAreaElement>) => {
    const updatedEdit: Edit = { id: proposalId, value: evt.target.value };
    dispatch(setEditForProposal(updatedEdit));
};

Property 'target' does not exist on type 'ChangeEventHandler<HTMLTextAreaElement>'

What's the correct way to type this?

Use

const updateEdit = (evt: React.ChangeEvent<HTMLTextAreaElement>) => {

The reason is you typed it as a ChangeEventHandler , which means a function that takes in a ChangeEvent . Or you could type the function as the handler

const updateEdit: React.ChangeEventHandler<HTMLTextAreaElement> = (evt) => {

I think you are typing the React.ChangeEventHandler in wrong place. should be

 const updateEdit: React.ChangeEventHandler<HTMLTextAreaElement>=(event){}

it is for handler itself but you are using for the argument of the function

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM