【问题标题】:TS2339: Property 'focus' does not exist on type '{}'. with React typescriptTS2339:类型“{}”上不存在属性“焦点”。使用 React 打字稿
【发布时间】:2019-08-16 03:35:39
【问题描述】:

我有一个 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 '{}'.

什么是问题?

【问题讨论】:

  • 另一种选择是this.inputRef = React.createRef&lt;HTMLInputElement | null&gt;(null)...

标签: reactjs typescript typescript-typings typescript2.0


【解决方案1】:

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

public inputRef: React.RefObject&lt;{}&gt;; 的正确行应该是:

  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()
  ...

【讨论】:

  • 为什么是this.inputRef.current.select()
  • 首先,您不需要构造函数来创建引用。只需在声明inputRef 时执行此操作。接下来,用if (this.inputRef.current) { ... }componentDidMount() 中的代码括起来,以确保它不为空。另请阅读medium.com/@martin_hotell/…
猜你喜欢
  • 2020-12-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-10
  • 2021-01-05
  • 2016-12-12
  • 1970-01-01
  • 2016-08-11
相关资源
最近更新 更多