reactjs —— useRef:变化的量
原文:
https://www.react.express/hooks/useref
useRef
With useRef
we can create a mutable value that exists for the lifetime of the component instance.
We start by wrapping a value, e.g. 42
, with: const myRef = useRef(42)
. Then, we use myRef.current
to access or update the mutable value.
All React components can be passed a ref using the ref
prop, in which case React will automatically assign the instance of the component, or the underlying DOM node, to myRef.current
. We often do this to access imperative DOM node APIs, such as calling focus
on an input element, or measuring an element with getBoundingClientRect()
.
Mutable value example
In this example, we store the return value of setInterval
, which is an interval id, so that we can later call clearInterval
.
import React, { useState, useRef, useEffect } from 'react' import { render } from 'react-dom' function App() { const intervalRef = useRef() const [count, setCount] = useState(0) useEffect(() => { intervalRef.current = setInterval(() => setCount(count => count + 1), 1000) return () => { clearInterval(intervalRef.current) } }, []) return ( <> <div style={{ fontSize: 120 }}>{count}</div> <button onClick={() => { clearInterval(intervalRef.current) }} > Stop </button> </> ) } render(<App />, document.querySelector('#app'))