简体   繁体   中英

wrong when using document in VScode

I'm using React and I want to use document.querySelector in componentDidMount.

The code I wrote can run correctly in browser.

Here is my code:

  componentDidMount() {
    document.querySelector('#text').addEventListener('keyup', (e)=>{
      console.log(e.key);
    })
  }
  componentDidUnMount() {
    document.querySelector('#text').removeEventListener('keyup');
  }

e.key can be shown in browser. But VScode just shows it is error. Questions just showed in componentDidMount() and componentDidUnMount() . It says that object may be 'null'. I want to know how to cancel this error.

You are using it the wrong way, react uses handlers to know what to do when some event takes place. Event may be onChange, onKeyUp, onKeyDown.

Working example below for the functionality using React.

import React from "react";
import ReactDOM from "react-dom";

class App extends React.Component {
  handleLoginKeyUp = e => {
    console.log(e.keyCode);
  };
  render() {
    return <input type="text" onKeyUp={this.handleLoginKeyUp} />;
  }
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

Hope that helps!!!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM