情况 1:在函数组件外部使用 let 变量
https://codepen.io/evan-jin/pen/VwWOPJV?editors=0010
案例2:在父函数组件中使用React.useRef
https://codepen.io/evan-jin/pen/VwWOpvg?editors=0010
情况1
let cursorTimer = null // << this is the point for 1 case
const Item = ({ num }) => {
const [hoverItem, setHoverItem] = useState(null)
const addCursor = useCallback(() => {
clearTimeout(cursorTimer)
cursorTimer = null
cursorTimer = setTimeout(() => {
document.body.style.cursor = 'wait'
}, 10)
}, [])
const removeCursor = useCallback(() => {
if (cursorTimer === null) return
cursorTimer = setTimeout(() => {
document.body.style.cursor = 'grab'
}, 500)
}, [])
useEffect(() …Run Code Online (Sandbox Code Playgroud)