reactjs - 我应该使用 TypeScript 输入什么类型的 react-bootstrap 事件?
问题描述
我正在使用 react-bootstrap lib,需要使用输入组件。我知道如何输入一个简单的输入,但有一个问题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" | “表格” | “风格” | “标题” | “模式” | "参考" | “钥匙” | “默认检查” | ... 268 更多... | "width"> & BsPrefixProps<...> & FormControlProps' 缺少来自类型 'HTMLInputElement' 的以下属性:align、autocomplete、autofocus、dirName 等 245 个。
那么怎么做而不使用任何类型呢?它应该是别名 HTMLInputElement 等等吗?
解决方案
您正在寻找 a React.ChangeEvent
,而不是 a 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))
}
推荐阅读
- django - 距离 Postgis Django Postgres
- sql - 在 SQL (Snowflake) 中将一行转换为布尔变量`
- google-cloud-platform - 当没有数据上传到 GCP 中的 BigQuery 表时创建警报
- tensorflow - Tensorflow mobilenet错误找不到输入层:函数'connect'中的MultipleGridAnchorGenerator/Shape_5
- mongodb - react native 无法从设备访问数据库
- r - 如何在 RStudio 中使用列作为 x 轴
- python - 在不重写的情况下更新不等式的布尔值
- python - 如何在不导入诗歌的情况下检查诗歌锁文件的新鲜度
- plesk - 使用 Plesk Rest API 获取域使用统计信息
- discord.js - 当我对选定的表情符号做出反应时,试图建立一个批准系统并且无法让机器人识别