预期
能够使用 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>'
最佳答案
这是在 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/