我正在尝试将数据与打字稿一起引用到 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
发布评论