简体   繁体   中英

Property does not exist on type - TypeScript

Created custom Form component which supposed to change its data when child inputs change.

Long story short:

在此处输入图片说明

In the current context currentTarget is the form, target is the input which triggered the event. target is exactly what I need - since I can then update the data:

this.setState({
  data: {
    [e.target.name]: e.target.value
  }
});

Any ideas?

  • Wrong event type?
  • Any way to cast in TypeScript (already tried)?
  • Wrong approach?

EDIT: something like this works, but this is just wrong:

handleChange(e: React.FormEvent) { let foo: any = e; this.setState({ data: { [foo.target.name]: foo.target.value } }); }

After some experimenting:

handleChange(e: React.FormEvent<HTMLFormElement>) { let name: string = (e.target as HTMLFormElement).name; let value: string = (e.target as HTMLFormElement).value; this.setState({ data: { [name]: value } });

It makes sense, since in this case the HTMLInputElement ( target ) is accessed as HTMLFormElement (listener).

May be there is more elegant solution but this kinda works.

How do you invoke your function handleChange?

i guess you are doing something like this:

onChange={this.handleChange()}

but you must do it:

onChange={this.handleChange)}

In fact, you have to pass the reference of the function, and not to invoke the function

Change the params to handleChange(e: React.FormEvent<HTMLFormElement>) and use e.currentTarget.name .

@thurt explain why in this related SO question , I also found some helpful comments in the type definition file here .

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