类型“null”不可分配给类型“HTMLInputElement”ReactJs
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/48488701/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Type 'null' is not assignable to type 'HTMLInputElement' ReactJs
提问by Abhinav1singhal
I am trying to reference data into reactJS along with typescript. While doing this I am getting below error
我正在尝试将数据与打字稿一起引用到 reactJS 中。在执行此操作时,我收到以下错误
Type 'null' is not assignable to type 'HTMLInputElement'
Please let me know what exactly incorrect here, I used documentaiton from React https://reactjs.org/docs/refs-and-the-dom.htmlbut I think I am doing something wrong here. Below is the scope snippet
请让我知道这里到底有什么不正确,我使用了 React https://reactjs.org/docs/refs-and-the-dom.html 中的文档, 但我认为我在这里做错了。以下是范围片段
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?
知道我在这里可能缺少什么吗?
回答by lleon
The error is produced becase the types definitions says input can be nullor a HTMLInputElement
产生错误是因为类型定义说输入可以是null或HTMLInputElement
You can set "strict": falsein your tsconfig.json
你可以"strict": false在你的tsconfig.json
Or you can force the input to be HTMLInputElementtype
或者您可以强制输入为HTMLInputElement类型
<input ref={thisInput => (this.textInput = thisInput as HTMLInputElement)} type="text" className="form-control" placeholder="Search" />
This way is also valid (using definite assignment assertions (typescript >= 2.7))
这种方式也是有效的(使用明确的赋值断言(typescript >= 2.7))
<input ref={thisInput => (this.textInput = thisInput!)} type="text" className="form-control" placeholder="Search" />
回答by Fenton
This is, indeed, caused by you correct and commendable use of:
这确实是由于您正确且值得称道的使用了:
"strict": "true"
Which sets a few rules including the all important:
其中设定了一些规则,包括所有重要的:
"strictNullChecks": "true"
"strictNullChecks": "真"
Handling Potential Nulls
处理潜在的空值
The correct way to handle this is to check that the element isn't in fact null, because almost every method you use to query an element may fail to find one.
处理这个问题的正确方法是检查元素实际上不是空的,因为几乎所有用于查询元素的方法都可能无法找到。
In the example below, the if-statement acts as a type guard, so the type of HTMLElement | nullis narrowed to just HTMLElement.
在下面的示例中, if 语句充当类型保护,因此类型 ofHTMLElement | null缩小为 just HTMLElement。
const elem = document.getElementById('test');
if (elem) {
elem.innerHTML = 'Type here is HTMLElement, not null';
}
Handling HTML Element Types
处理 HTML 元素类型
To narrow the type from HTMLElementto HTMLInputElement, you can take an "I know better" approach and use a type assertion (making a class of subtle errors possible):
要将类型从 缩小HTMLElement到HTMLInputElement,您可以采用“我知道更好”的方法并使用类型断言(使一类细微错误成为可能):
const example = <HTMLInputElement> elem;
Or you can use a custom type guard to do it properly, the below example takes HTMLElement | nulland narrows it to HTMLInputElementif it isn't null, and has the correct tag name:
或者您可以使用自定义类型保护来正确执行此操作,下面的示例将HTMLElement | null其缩小HTMLInputElement为不为空,并且具有正确的标记名称:
function isInputElement(elem: HTMLElement | null): elem is HTMLInputElement {
if (!elem) {
// null
return false;
}
return (elem.tagName === 'INPUT')
}
The updated type guard call looks like this:
更新后的类型保护调用如下所示:
const elem = document.getElementById('test');
if (isInputElement(elem)) {
console.log(elem.value);
}
回答by Lakkanna walikar
I solved in react using if condition before i use ref
我在使用 ref 之前使用 if 条件解决了反应
if (this.ref.current) {
this.editor = monaco.editor.create(
this.ref.current,
{ automaticLayout: true }
);
monaco.editor.setTheme('vs-dark');
this.editor.setModel(this.model);
}

