Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

typescript - Type 'null' is not assignable to type 'HTMLInputElement' 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'

Please let me know what exactly incorrect here, I used documentaiton from React https://reactjs.org/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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The error is produced becase the types definitions says input can be null or a HTMLInputElement

You can set "strict": false in your tsconfig.json

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" />

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" />

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...