C
C
chrome1232020-08-08 10:26:30
React
chrome123, 2020-08-08 10:26:30

How to handle window or document event in react js?

There is a small code in react js

class Task extends  React.Component {

          constructor(props) {
              super(props);

              this.state = {
                  keyDown: false, // по умолчанию, игра остановлена
             
              }

          }
         editkeyDown = () =>{
              this.setState({keyDown:  this.state.keyDown ? false : true})

          }


          render() {

              return (

                      <div id="map"  className="Box">

                      </div>

              )
          }
      }

      const app = document.getElementById("example");
      ReactDOM.render(
              <div className="field">
                   <Task />
              </div>,
          app
      );


How I want that at the time of the event

$(window).on("keydown", function(event){
      console.log(event);
  });


The value of this.state.keyDown was changed

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2020-08-08
@chrome123

onKeyDown = ({ key }) => {
  this.setState(() => ({
    keyDown: key,
  }));
}

componentDidMount() {
  document.addEventListener('keydown', this.onKeyDown);
}

componentWillUnmount() {
  document.removeEventListener('keydown', this.onKeyDown);
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question