简体   繁体   English

在VScode中使用文档时出错

[英]wrong when using document in VScode

I'm using React and I want to use document.querySelector in componentDidMount. 我正在使用React,我想在componentDidMount中使用document.querySelector。

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. e.key可以显示在浏览器中。 But VScode just shows it is error. 但是VScode只是表明这是错误的。 Questions just showed in componentDidMount() and componentDidUnMount() . 刚刚在componentDidMount()componentDidUnMount()显示的问题。 It says that object may be 'null'. 它说对象可能是“ 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. 您以错误的方式使用它,React使用处理程序来知道某个事件发生时该怎么办。 Event may be onChange, onKeyUp, onKeyDown. 事件可能是onChange,onKeyUp,onKeyDown。

Working example below for the functionality using React. 以下是使用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!!! 希望有帮助!!!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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