我正在尝试将数据与打字稿一起引用到 reactJS 中。这样做时,我遇到了错误
Type 'null' is not assignable to type 'HTMLInputElement'
请让我知道这里到底有什么不正确的地方,我使用了来自 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}>
...............
知道我在这里可能缺少什么吗?
原文由 athenatechie 发布,翻译遵循 CC BY-SA 4.0 许可协议
产生错误是因为类型定义说输入可以是
null
或HTMLInputElement
您可以设置
"strict": false
在您的tsconfig.json
或者您可以强制输入为
HTMLInputElement
类型这种方式也是有效的( 使用明确的赋值断言(打字稿> = 2.7) )