我創建了一個名為 text 的變數和一個名為 setText 的鉤子。我正在使用它來更改表單輸入欄位的值。
我如何設定該文本將是字串型別?
這是我嘗試過的:
interface TextInterface {
text: string | null,
setText: (value: string) => void,
}
const [ text, setText ] = useState<TextInterface>('');
但是在執行此操作時會顯示以下錯誤:“字串”型別的引數不可分配給“文本介面”型別的引數 | (() => TextInterface)'。
它還在輸入欄位內和 handleText 函式內顯示錯誤(用于輸入欄位內的 onchange)。
功能:
const handleText = (e: React.FocusEvent<HTMLInputElement>): void => {
setText(e.currentTarget.value);
}
顯示錯誤:“字串”型別的引數不可分配給“SetStateAction”型別的引數
輸入欄位:
<input type="text" value={ text } onChange={ handleText } />
錯誤:型別 'TextInterface' 不可分配給型別 'string | 號碼 | 只讀字串[] | 不明確的'。
uj5u.com熱心網友回復:
const [ text, setText ] = useState<TextInterface>('');
你很接近,但useState泛型并不希望你傳入一個描述狀態和狀態設定器的型別。您只需要指定狀態的型別,如下所示:
const [ text, setText ] = useState<string | null>('');
如果null不可能,您也可以省略顯式型別,打字稿會推斷出型別為string
const [ text, setText ] = useState('');
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/464701.html
