useRef
用于在函数组件中创建一个可持久化的引用,一般用于访问 DOM 元素或保持数据的持久性。
useRef 不会引起组件的重新渲染,
index.tsx
import React, { useRef } from 'react';
function MyApp() {
const inputRef = useRef(null);
const timerIdRef = useRef(null);
const handleButtonClick = () => {
inputRef.current.focus();
timerIdRef.current = setInterval(() => {
console.log('Timer is running');
}, 1000);
};
return (
<div>
<input ref={inputRef} />
<button onClick={handleButtonClick}>Focus Input</button>
</div>
);
}
export default MyApp;