Abh*_*hal 9 reference typescript reactjs
我试图将数据引入reactJS以及打字稿.在这样做时,我得到了以下错误
Type 'null' is not assignable to type 'HTMLInputElement'
Run Code Online (Sandbox Code Playgroud)
请告诉我这里究竟有什么不正确的地方,我使用了React https://reactjs.org/docs/refs-and-the-dom.html中的 documentaiton, 但我觉得我在这里做错了.以下是范围片段
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}>
...............
Run Code Online (Sandbox Code Playgroud)
知道我在这里缺少什么吗?
lle*_*eon 12
由于类型定义表明输入可以是null
a或a,因此产生错误HTMLInputElement
你可以设置"strict": false
在你的tsconfig.json
或者您可以强制输入HTMLInputElement
类型
<input ref={thisInput => (this.textInput = thisInput as HTMLInputElement)} type="text" className="form-control" placeholder="Search" />
Run Code Online (Sandbox Code Playgroud)
这种方式也有效(使用明确的赋值断言(typescript> = 2.7))
<input ref={thisInput => (this.textInput = thisInput!)} type="text" className="form-control" placeholder="Search" />
Run Code Online (Sandbox Code Playgroud)
这确实是由于您正确且值得称道的使用了:
"strict": "true"
Run Code Online (Sandbox Code Playgroud)
其中设定了一些规则,包括所有重要的规则:
“strictNullChecks”:“真”
处理这个问题的正确方法是检查元素实际上不是空的,因为几乎所有用于查询元素的方法都可能无法找到。
在下面的示例中, if 语句充当类型保护,因此类型 ofHTMLElement | null
缩小为 just HTMLElement
。
const elem = document.getElementById('test');
if (elem) {
elem.innerHTML = 'Type here is HTMLElement, not null';
}
Run Code Online (Sandbox Code Playgroud)
要将类型从 缩小HTMLElement
到HTMLInputElement
,您可以采用“我知道更好”的方法并使用类型断言(使一类细微错误成为可能):
const example = <HTMLInputElement> elem;
Run Code Online (Sandbox Code Playgroud)
或者您可以使用自定义类型保护来正确执行此操作,下面的示例将HTMLElement | null
其范围缩小到HTMLInputElement
它不为空,并且具有正确的标记名称:
function isInputElement(elem: HTMLElement | null): elem is HTMLInputElement {
if (!elem) {
// null
return false;
}
return (elem.tagName === 'INPUT')
}
Run Code Online (Sandbox Code Playgroud)
更新后的类型保护调用如下所示:
const elem = document.getElementById('test');
if (isInputElement(elem)) {
console.log(elem.value);
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
15345 次 |
最近记录: |