首页 > 解决方案 > TS2339:类型“{}”上不存在属性“焦点”。使用 React 打字稿

问题描述

我有 JSX 类的打字稿代码

export class SearchForm extends React.PureComponent<Props, State> {

  public inputRef: React.RefObject<{}>;

  constructor(props: any) {
    super(props)
    this.inputRef = React.createRef()
  }

  public componentDidMount(): void {
      this.inputRef.current.focus()
      this.inputRef.current.select()
  ...

现在,当我尝试编译这段代码时,我遇到了一堆错误:

ERROR in ...
TS2339: Property 'className' does not exist on type '{}'.

ERROR in ...
TS2339: Property 'focus' does not exist on type '{}'.

什么是问题?

标签: reactjstypescripttypescript-typingstypescript2.0

解决方案


错误出现在 的类型定义中inputRef: React.RefObject<{}>;,这是自动修复类型问题的默认建议。类型RefObject<{}>不可分配给 type RefObject<HTMLInputElement>。Type{}缺少 type 中的以下属性HTMLInputElement:accept、align、alt、autocomplete 等。

正确的行public inputRef: React.RefObject<{}>;应该是:

  public inputRef: React.RefObject<HTMLInputElement>;

这段代码看起来像:

export class SearchForm extends React.PureComponent<Props, State> {

  public inputRef: React.RefObject<HTMLInputElement>;

  constructor(props: any) {
    super(props)
    this.inputRef = React.createRef()
  }

  public componentDidMount(): void {
      this.inputRef.current.focus()
      this.inputRef.current.select()
  ...

推荐阅读