为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

紫衣仙女 2021-05-06 14:42:51
给出下面的例子#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总是初始值。
查看完整描述

2 回答

  • 2 回答
  • 0 关注
  • 115 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信