给出下面的例子
#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>
现在,我将把按键监听器移到窗口,应该做同样的事情。
但这并不num
总是初始值。
相关分类