我的代碼是
import React, { useState } from "react";
function App() {
const [inputValue, setInputValue] = useState<string>("");
const handleInputValue = (e: React.ChangeEventHandler<HTMLInputElement>) => {
setInputValue(e.target.value);
};
return (
<div className="App">
<div>
<input name="name" onChange={handleInputValue} />
</div>
<p>{inputValue}</p>
</div>
);
}
export default App;
當我使用e:any運行良好但使用 e 型別時 React.ChangeEventHandler 不起作用
這是錯誤資訊
“ChangeEventHandler”型別上不存在屬性“目標”。
Type '(e: React.ChangeEventHandler<HTMLInputElement>) => void' is not assignable to type 'ChangeEventHandler<HTMLInputElement>'.
Types of parameters 'e' and 'event' are incompatible.
Type 'ChangeEvent<HTMLInputElement>' is not assignable to type 'ChangeEventHandler<HTMLInputElement>'.
Type 'ChangeEvent<HTMLInputElement>' provides no match for the signature '(event: ChangeEvent<HTMLInputElement>): void'.
27 | <div>
> 28 | <input name="name" onChange={handleInputValue} />
| ^^^^^^^^
29 | </div>
uj5u.com熱心網友回復:
const handleInputValue = (e: React.ChangeEventHandler<HTMLInputElement>) => {
setInputValue(e.target.value);
};
該型別ChangeEventHandler適用于整個函式,而不僅僅是傳遞給它的事件。所以你要么需要這樣做:
const handleInputValue: React.ChangeEventHandler<HTMLInputElement> = (e) => {
setInputValue(e.target.value);
};
或這個:
const handleInputValue = (e: React.ChangeEvent<HTMLInputElement>) => {
setInputValue(e.target.value);
};
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/419745.html
標籤:
