reactjs - 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 '{}'.
什么是问题?
解决方案
错误出现在 的类型定义中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()
...
推荐阅读
- statistics - 严格有界结果变量的 beta 回归与线性回归 [0,1]
- javascript - 在向 Firebase-Cloud-Function 端点发布请求时收到“500 内部服务器错误”
- r - RQDA 不读取 UTF-8 编码的 .txt 中导入的 UTF-8 字符
- django - 如何验证插入或返回错误
- sql - Postgres 中的新对象不会替换为已删除的对象
- rollup - 如何在带有汇总的 sapper-template 中使用 postcss 处理 css
- javascript - 数据未在阵列上更新
- java - 使用 JDBC 调用 SQL Server 时无法解决未分类的 SQLException
- jquery - 在我的情况下,如何在 ASP.Net 视图页面的 foreach 中制作 If 语句?
- ruby-on-rails - 如何使用 ActionText 显示嵌入视频