小编典典

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

reactjs

我正在尝试将数据与打字稿一起引用到reactJS中。在这样做时,我得到以下错误

Type 'null' is not assignable to type 'HTMLInputElement'

请让我知道这里到底有什么不正确,我使用了来自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}>

   ...............

知道我在这里可能会缺少什么吗?


阅读 1311

收藏
2020-07-22

共1个答案

小编典典

如果类型定义说输入可以是null或则产生错误HTMLInputElement

您可以"strict": falsetsconfig.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" />
2020-07-22