【发布时间】:2018-07-07 09:46:23
【问题描述】:
我正在尝试将数据与 typescript 一起引用到 reactJS 中。这样做时,我遇到了错误
Type 'null' is not assignable to type 'HTMLInputElement'
请让我知道这里有什么不正确的地方,我使用了 React 的文档 https://reactjs.org/docs/refs-and-the-dom.html 但我认为我在这里做错了什么。 下面是范围sn-p
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}>
...............
知道我在这里可能缺少什么吗?
【问题讨论】:
-
只有在更改路线时才会发生,我的意思是在卸载组件时?
-
@MayankShukla 是的。
-
也可以这样写:private textInput: HTMLInputElement |空;
标签: reactjs typescript reference