反应无法从文档/窗口按键访问状态

给出下面的例子

#app div {

  padding: 10px;

  border: 1px solid;

  margin: 10px 0;

}


div:focus {

  background: red;

}


div:focus:before {

  content: "focused";

  display: block;

}

<div id="app"></div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.6/umd/react.production.min.js"></script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.6/umd/react-dom.production.min.js"></script>

<script src="https://unpkg.com/babel-standalone@6.15.0/babel.min.js"></script>


<script type="text/babel">

  let { useState, useRef, Fragment } = React; 

  let App = () => { 

    let [, forceUpdate] = useState(); 

    let [num, setNum] = useState(0); 

    let history = useRef('null'); 

    

    let keyPressHandler = () => { 

    history.current = num; 

    

    // just to force an update 

    forceUpdate(Date.now());

  }; 

  

  return (

  <Fragment>

    <button onClick={()=>{setNum(Date.now())}}>update state</button>

    <div tabindex="0" onKeyPress={keyPressHandler}>this div has a keypress listener. <br/>for now whatever key you press it will save the state in a ref, that changes on the button click. <br/>Click the button to change the state then focus this div then press any key to save the state in the ref</div>

    <div>State&nbsp;&nbsp;&nbsp;&nbsp;: {num}</div>

    <div>History: {history.current}</div>

  </Fragment>

  ); 

}; 


ReactDOM.render(<App />, document.querySelector("#app"));

</script>

现在,我将把按键监听器移到窗口,应该做同样的事情。

但这并不num总是初始值。


紫衣仙女
浏览 116回答 2
2回答
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript