useRef 可以在函数组件中存储可变值的方式。与useState的不同之处是,它不会引起组件的重新渲染。
import React, { useState, useEffect, useRef } from 'react';
function App() {
const [count, setCount] = useState(0);
const intervalRef = useRef(null);
useEffect(() => {
intervalRef.current = setInterval(() => {
setCount(c => c + 1);
}, 1000);
return () => clearInterval(intervalRef.current);
}, []);
return (
<div>
<p>{count}</p>
<button onClick={() => clearInterval(intervalRef.current)}>
Stop timer
</button>
</div>
);
}
import React, { useState, useEffect, useRef } from 'react';
function App() {
const [count, setCount] = useState(0);
const prevCountRef = useRef(null);
useEffect(() => {
prevCountRef.current = count;
});
const prevCount = prevCountRef.current;
return (
<div>
<p>Current count: {count}</p>
{prevCount && (
<p>Previous count: {prevCount}</p>
)}
<button onClick={() => setCount(c => c + 1)}>
Increase count
</button>
</div>
);
}
import React, { useRef } from 'react';
function App() {
const inputRef = useRef(null);
function handleFocus() {
inputRef.current.style.backgroundColor = 'yellow';
}
function handleBlur() {
inputRef.current.style.backgroundColor = 'white';
}
return (
<>
<input type="text" ref={inputRef} onFocus={handleFocus} onBlur={handleBlur} />
<button onClick={() => inputRef.current.focus()}>
Focus input
</button>
</>
);
}