首页 > 解决方案 > 我应该使用 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 等等吗?

标签: reactjstypescriptreact-bootstrap

解决方案


您正在寻找 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))
}

推荐阅读