类型“null”不可分配给类型“HTMLInputElement”ReactJs

新手上路,请多包涵

我正在尝试将数据与打字稿一起引用到 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 许可协议

阅读 1.1k
1 个回答

产生错误是因为类型定义说输入可以是 nullHTMLInputElement

您可以设置 "strict": false 在您的 tsconfig.json

或者您可以强制输入为 HTMLInputElement 类型

<input ref={thisInput => (this.textInput = thisInput as HTMLInputElement)} type="text" className="form-control" placeholder="Search" />

这种方式也是有效的( 使用明确的赋值断言(打字稿> = 2.7)

 <input ref={thisInput => (this.textInput = thisInput!)} type="text" className="form-control" placeholder="Search" />

原文由 lleon 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进