如何从React Typescript的输入字段中获取值?

时间:2020-05-20 16:14:36

标签: reactjs typescript

如何从React Typescipt的输入字段中获取数据?

代码:

import React, { useState } from 'react'

const AuthPage: React.FC = () => {
  const [form, setForm] = useState({
    email: '',
    password: '',
  })

  const changeHandler = (event: React.KeyboardEvent) => {
    setForm({ ...form, [event.target.name]: event.target.value })
  }

  const showState = () => {
    console.log(form)
  }

  return (
    <div className="row">
      <div className="col s6 offset-s3">
        <h1>URL Shortener</h1>
        <div className="card blue darken-4">
          <div className="card-content white-text">
            <span className="card-title">Authorization</span>
            <div>
              <div className="input-field">
                <input
                  placeholder="Enter Email"
                  id="email"
                  type="text"
                  name="email"
                  className="yellow-input"
                  onChange={changeHandler}
                />
              </div>
              <div className="input-field">
                <input
                  placeholder="Enter Password"
                  id="password"
                  type="password"
                  name="password"
                  className="yellow-input"
                  onChange={changeHandler}
                />
              </div>
            </div>
          </div>
          <div className="card-action">
            <button className="btn yellow darken-4" style={{ marginRight: 10 }}>
              Sign in
            </button>
            <button onClick={showState} className="btn grey lighten-1 black-text">
              Sign up
            </button>
          </div>
        </div>
      </div>
    </div>
  )
}

export default AuthPage

这是错误消息:

"Property 'name' does not exist on type 'EventTarget'.  TS2339".
"Property 'name' does not exist on type 'EventTarget'.  TS2339".
and second error "Type '(event: React.KeyboardEvent) => void' is not assignable to type '(event: ChangeEvent<HTMLInputElement>) => void'.
  Types of parameters 'event' and 'event' are incompatible.
    Type 'ChangeEvent<HTMLInputElement>' is missing the following properties from type 'KeyboardEvent<Element>': altKey, charCode, ctrlKey, getModifierState, and 8 more.ts(2322)
index.d.ts(2101, 9): The expected type comes from property 'onChange' which is declared here on type 'DetailedHTMLProps<InputHTMLAttributes<HTMLInputElement>, HTMLInputElement>'"

1 个答案:

答案 0 :(得分:0)

-generic type。您可以指定其所附加的元素类型,例如:React.KeyboardEvent

此外,您可能需要将React.KeyboardEvent<HTMLInputElement>(由于event delegation而可能是注册事件处理程序的元素)更改为event.target(保证是其注册的元素。