[英]App breaking when trying to use usetState in React/TypeScript app
能夠使用useState
在功能性React組件內設置電子郵件和密碼var。
然后使用對輸入的onChange改變這些變量,然后經由發送的那些變量的結果到父類signIn
功能。
在onChange
突出顯示了一個打字稿錯誤,並且應用程序中斷了。
碼
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屬性)React.InputHTMLAttributes.onChange ?:((事件:React.ChangeEvent)=>無效)| 未定義類型'調度>不是分配給輸入“(事件:的ChangeEvent)=>無效”。 參數“值”和“事件”的類型不兼容。 類型'ChangeEvent'不能分配給類型'SetStateAction'。 類型'ChangeEvent'不能分配給類型'(prevState:string)=> string'。 類型'ChangeEvent'不提供簽名'(prevState:string):string'的匹配項。ts(2322)index.d.ts(1976,9):預期的類型來自屬性'onChange',在此聲明該類型'DetailedHTMLProps,HTMLInputElement>'
這是在onChange中設置setState的方式:
<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)}
/>
另一個具有提取功能並使用currying方法可重用的版本如下:
export default ({ signIn }) => {
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const handleChange = setterFunc => e => {
const value = e.target.value;
setterFunc(value);
}
return (
<>
<input
type="text"
placeholder="Email"
value={email}
onChange={handleChange(setEmail)}
/>
<input
type="password"
placeholder="Password"
value={password}
onChange={handleChange(setPassword)}
/>
</>
)
}
這是實時版本: https : //stackblitz.com/edit/react-rf4bhw
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.