![](/style/images/good.png)
![](/style/images/bad.png)
Typography: React to event types
source link: https://www.codesd.com/item/typography-react-to-event-types.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
Typography: React to event types
What is the correct type for React events. Initially I just used any
for the sake of simplicity. Now, I am trying to clean things up and avoid use of any
completely.
So in a simple form like this:
export interface LoginProps {
login: {
[k: string]: string | Function
uname: string
passw: string
logIn: Function
}
}
@inject('login') @observer
export class Login extends Component<LoginProps, {}> {
update = (e: React.SyntheticEvent<EventTarget>): void => {
this.props.login[e.target.name] = e.target.value
}
submit = (e: any): void => {
this.props.login.logIn()
e.preventDefault()
}
render() {
const { uname, passw } = this.props.login
return (
<div id='login' >
<form>
<input
placeholder='Username'
type="text"
name='uname'
value={uname}
onChange={this.update}
/>
<input
placeholder='Password'
type="password"
name='passw'
value={passw}
onChange={this.update}
/>
<button type="submit" onClick={this.submit} >
Submit
</button>
</form>
</div>
)
}
}
What type do I use here as event type?
React.SyntheticEvent<EventTarget>
does not seem to be working as I get an error that name
and value
do not exist on target
.
More generalised answer for all events would be really appreciated.
Thanks
The SyntheticEvent interface is generic:
interface SyntheticEvent<T> {
...
currentTarget: EventTarget & T;
...
}
And the currentTarget
is an intersection of the generic constraint and EventTarget
.
Also, since your events are caused by an input element you should use the FormEvent
(in definition file, the react docs).
Should be:
update = (e: React.FormEvent<HTMLInputElement>): void => {
this.props.login[e.currentTarget.name] = e.currentTarget.value
}
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK