打字稿:反应事件类型 [英] Typescript: React event types

查看:94
本文介绍了打字稿:反应事件类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

React事件的正确类型是什么。最初我只是为了简单起见使用了任何。现在,我正在尝试清理并完全避免使用任何

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< Ev entTarget> 似乎没有工作,因为我收到 name value 的错误在目标上不存在。

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.

谢谢

推荐答案

SyntheticEvent 接口是通用的:

interface SyntheticEvent<T> {
    ...
    currentTarget: EventTarget & T;
    ...
}

以及 currentTarget 是泛型约束与 EventTarget 的交集。

此外,由于您的事件是由输入元素引起的,您应该使用 FormEvent 中的rel =noreferrer>,反应文档)。

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).

应该是:

update = (e: React.FormEvent<HTMLInputElement>): void => {
    this.props.login[e.currentTarget.name] = e.currentTarget.value
}

这篇关于打字稿:反应事件类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆