給出下面的例子#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 : {num}</div> <div>History: {history.current}</div> </Fragment> ); }; ReactDOM.render(<App />, document.querySelector("#app"));</script>現(xiàn)在,我將把按鍵監(jiān)聽器移到窗口,應該做同樣的事情。但這并不num總是初始值。
反應無法從文檔/窗口按鍵訪問狀態(tài)
紫衣仙女
2021-05-06 14:42:51