reactjs - 在 TypeScript 中,我應該為 react-bootstrap 輸入事件使用哪種類型?
我正在使用 react-bootstrap 函式庫,並需要使用一個輸入元件。我知道如何輸入一個簡單的輸入框,但在使用 FormControl 時遇到問題
class Search extends Component<Props, { searchInput: string }> {
static defaultProps = {}
state = {
searchInput: ""
}
// This one works for input
searchInputSimple = (e: React.FormEvent<HTMLInputElement>): void => {
const { getSearch } = this.props
this.setState(
{ searchInput: e.currentTarget.value },
(): void => getSearch(this.state.searchInput)
)
}
// for FormControl. What can I use exept any?
searchInput = (e: React.FormEvent<any>): void => {
const { getSearch } = this.props
this.setState(
{ searchInput: e.currentTarget.value },
(): void => getSearch(this.state.searchInput)
)
}
render() {
const { searchInput } = this.state
return (
<>
<InputGroup className="mb-3">
<FormControl placeholder="Search" value={searchInput} onChange={this.searchInput} />
</InputGroup>
<input
placeholder="Search"
value={searchInput}
onChange={this.searchInputSimple}
className="form-control"
/>
</>
)
}
}
我試著去理解並查看 FormControl.d.ts
import Feedback from './Feedback';
import { BsPrefixComponent } from './helpers';
interface FormControlProps {
innerRef?: React.LegacyRef<this>;
size?: 'sm' | 'lg';
plaintext?: boolean;
readOnly?: boolean;
disabled?: boolean;
value?: string;
onChange?: React.FormEventHandler<this>;
type?: string;
id?: string;
isValid?: boolean;
isInvalid?: boolean;
}
declare class Form<
As extends React.ReactType = 'input'
> extends BsPrefixComponent<As, FormControlProps> {
static Feedback: typeof Feedback;
}
如果我只使用 HTMLInputElement,我會收到這個錯誤
類型錯誤:類型 '(e: FormEvent) => void' 無法分配給類型 '(event: FormEvent & FormControlProps>>) => void'。參數 'e' 和 'event' 的類型不兼容。類型 'FormEvent & FormControlProps>>' 無法分配給類型 'FormEvent'。類型 'Pick, HTMLInputElement>, "children" | "form" | "style" | "title" | "pattern" | "ref" | "key" | "defaultChecked" | ... 268 個更多 ... | "width"> & BsPrefixProps<...> & FormControlProps' 缺少類型 'HTMLInputElement' 的以下屬性:align、autocomplete、autofocus、dirName,以及其他 245 個更多。
那麼該如何做而不使用任何類型呢?它應該是一個 HTMLInputElement 的別名,還是需要其他東西?
答案#1
你正在尋找 React.ChangeEvent,而不是 React.FormEvent:
searchInput = (e: React.ChangeEvent<HTMLInputElement>): void => {
const { value } = e.currentTarget;
const { getSearch } = this.props;
this.setState(state => ({
...state,
searchInput: value
}), (): void => getSearch(this.state.searchInput))
}
答案#2
如果你以這種方式使用 React.ChangeEvent
(e: React.ChangeEvent<HTMLInputElement>)
請注意,在您的 HTML 代碼中不應以這種方式調用您的函數:
onChange={(e) => searchInput(e)}
改為這樣稱呼它:
onChange={searchInput}
