javascript - 尝试在 React/TypeScript 应用程序中使用 usetState 时应用程序崩溃

标签 javascript reactjs typescript react-hooks

预期

能够使用 useState 在功能性 React 组件内设置电子邮件和密码变量。

然后在输入上使用 onChange 来更改这些变量,然后通过 signIn 函数将这些变量的结果发送到父类。

结果

onChange 上突出显示了 typescript 错误,并且应用程序崩溃了。

代码

import React, {useState} from 'react'

import {
  AuthArea,
  AuthInputs,
  CreateNewAccount,
  FunctionButton
} from '../../styles'

interface IProps {
  signIn(email: string, password: string): void
}

export default ({ signIn }: IProps) => {
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');

  return (
    <AuthArea>
      <h1>Sign In</h1>
      <AuthInputs>
        <input
          type="text"
          placeholder="Email"
          value={email}
          onChange={setEmail}
        />
        <input
          type="password"
          placeholder="Password"
          value={password}
          onChange={setPassword}
        />
        <FunctionButton onClick={() => signIn(email, password)}>
          Sign In
        </FunctionButton>
        <a href="#">Forgot Password?</a>
      </AuthInputs>
      <CreateNewAccount>
        Create New Account
      </CreateNewAccount>
    </AuthArea>
  )
}

错误

(JSX attribute) React.InputHTMLAttributes.onChange?: ((event: React.ChangeEvent) => void) | undefined Type 'Dispatch>' is not assignable to type '(event: ChangeEvent) => void'. Types of parameters 'value' and 'event' are incompatible. Type 'ChangeEvent' is not assignable to type 'SetStateAction'. Type 'ChangeEvent' is not assignable to type '(prevState: string) => string'. Type 'ChangeEvent' provides no match for the signature '(prevState: string): string'.ts(2322) index.d.ts(1976, 9): The expected type comes from property 'onChange' which is declared here on type 'DetailedHTMLProps, HTMLInputElement>'

enter image description here

最佳答案

这是在 onChange 中设置状态的方法:

<input
     type="text"
     placeholder="Email"
     value={email}
     onChange={(e) => setEmail(e.target.value)}
/>
<input
     type="password"
     placeholder="Password"
     value={password}
     onChange={(e) => setPassword(e.target.value)}
/>

关于javascript - 尝试在 React/TypeScript 应用程序中使用 usetState 时应用程序崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57836693/

相关文章:

javascript - 从 React 中的两个测试库渲染助手组成单个渲染助手

javascript - Angular 2分配问题

javascript - 如何将值传递给其他 Controller ?

javascript - node.js + socket.io + redis + rails — 实时应用程序

javascript - 使用 p5.js 在图像上摆动形状

javascript - 如何从 Typescript 对象获取默认值?

typescript - 在多个 TypeScript 文件中声明和使用相同的命名空间

javascript - 导出时重命名下载文件

javascript - 使用 Jest 响应 js 测试 bool 属性

javascript - 如何将变量的值从子组件发送到父组件?