Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
266 views
in Technique[技术] by (71.8m points)

javascript - 打字稿:React事件类型(Typescript: React event types)

What is the correct type for React events.(React事件的正确类型是什么。)

Initially I just used any for the sake of simplicity.(最初,为了简单起见,我只是使用了any 。) Now, I am trying to clean things up and avoid use of any completely.(现在,我正在尝试清理并避免完全使用any东西。)

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 .(React.SyntheticEvent<EventTarget>似乎不起作用,因为我得到一个错误,即target上不存在namevalue 。)

More generalised answer for all events would be really appreciated.(对于所有事件的更笼统的回答,我们将不胜感激。)

Thanks(谢谢)

  ask by r.sendecky translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The SyntheticEvent interface is generic:(SyntheticEvent接口是通用的:)

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

And the currentTarget is an intersection of the generic constraint and EventTarget .(并且currentTarget是通用约束和EventTarget的交集。)


Also, since your events are caused by an input element you should use the FormEvent ( in definition file , the react docs ).(另外,由于事件是由输入元素引起的,因此应使用FormEvent在定义文件中react docs )。)

Should be:(应该:)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...