类型“null"不可分配给类型“HTMLInputElement"ReactJs

编程入门 行业动态 更新时间:2024-10-28 09:18:08
本文介绍了类型“null"不可分配给类型“HTMLInputElement"ReactJs的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在尝试将数据与打字稿一起引用到 reactJS 中.这样做时,我遇到以下错误

I am trying to reference data into reactJS along with typescript. While doing this I am getting below error

Type 'null' is not assignable to type 'HTMLInputElement'

请让我知道这里到底哪里不正确,我使用了 React 的文档reactjs/docs/refs-and-the-dom.html但我想我在这里做错了什么.以下是范围片段

Please let me know what exactly incorrect here, I used documentaiton from React reactjs/docs/refs-and-the-dom.html but I think I am doing something wrong here. Below is the scope snippet

class Results extends React.Component<{}, any> { private textInput: HTMLInputElement; ....... constructor(props: any) { super(props); this.state = { topics: [], isLoading: false }; this.handleLogin = this.handleLogin.bind(this); } componentDidMount() {.....} handleLogin() { this.textInput.focus(); var encodedValue = encodeURIComponent(this.textInput.value); ....... } render() { const {topics, isLoading} = this.state; if (isLoading) { return <p>Loading...</p>; } return ( <div> <input ref={(thisInput) => {this.textInput = thisInput}} type="text" className="form-control" placeholder="Search"/> <div className="input-group-btn"> <button className="btn btn-primary" type="button" onClick={this.handleLogin}> ...............

知道我在这里可能遗漏了什么吗?

Any idea what I may be missing here?

推荐答案

产生错误是因为类型定义说输入可以是 null 或 HTMLInputElement

The error is produced becase the types definitions says input can be null or a HTMLInputElement

您可以在 tsconfig.json 中设置 "strict": false

You can set "strict": false in your tsconfig.json

或者你可以强制输入为 HTMLInputElement 类型

Or you can force the input to be HTMLInputElement type

<input ref={thisInput => (this.textInput = thisInput as HTMLInputElement)} type="text" className="form-control" placeholder="Search" />

这种方式也是有效的(使用明确赋值断言 (typescript >= 2.7))

This way is also valid (using definite assignment assertions (typescript >= 2.7))

<input ref={thisInput => (this.textInput = thisInput!)} type="text" className="form-control" placeholder="Search" />

更多推荐

类型“null"不可分配给类型“HTMLInputElement"ReactJs

本文发布于:2023-11-14 02:30:53,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1585986.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:类型   不可分   null   quot   HTMLInputElement

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!