react useref
时间: 2025-01-12 14:39:42 浏览: 43
### React 中 `useRef` Hook 的用法
#### 定义与基本功能
`useRef` 是 React 提供的一个 Hook,用于创建一个可变的引用对象。这个对象在整个组件生命周期内保持不变,并且其 `.current` 属性可以保存任何类型的值。这使得 `useRef` 成为了存储 DOM 节点、计时器 ID 或者其他不触发重新渲染的数据的理想选择。
```javascript
import { useRef } from 'react';
function MyComponent() {
const myRef = useRef(null);
// 使用 ref 获取 DOM 元素并操作它
}
```
#### 实际应用场景
##### 场景一:访问DOM节点
当需要直接操纵某个特定的 HTML 元素时,可以通过给该元素设置 `ref={myRef}` 来获取到对应的 DOM 对象实例[^1]。
```jsx
const inputElement = useRef(null);
<button onClick={() => inputElement.current.focus()}>
Focus Input
</button>
<input ref={inputElement} />
```
##### 场景二:管理状态而不引起重绘
有时希望某些变量的变化不会导致组件重新渲染,这时就可以利用 `useRef` 存储这些数据。因为修改 `useRef().current` 不会引发新的渲染周期[^2]。
```jsx
let countRender = useRef(0);
function Counter(){
useEffect(() => {
console.log(`You've rendered ${countRender.current++}`);
});
return (
<div>Counter Component</div>
);
}
```
##### 场景三:跨多个子组件共享逻辑
虽然这里提到的是自定义 Hooks 可以用来分享逻辑,但是通过 `useImperativeHandle` 和 `forwardRef` 结合 `useRef` 同样能够实现类似的效果,在父级控制子级的行为而不需要传递回调函数作为 prop。
```jsx
// Child component that exposes imperative methods via forwardRef and useImperativeHandle.
const FancyInput = React.forwardRef((props, ref) => {
const inputRef = useRef();
useImperativeHandle(ref, () => ({
focus: () => {
inputRef.current.focus();
}
}));
return <input ref={inputRef} />;
});
// Parent component uses the child's exposed method through useRef.
class App extends React.Component {
constructor(props){
super(props);
this.inputEl = React.createRef();
}
render() {
return(
<>
<FancyInput ref={this.inputEl}/>
<button onClick={()=>{this.inputEl.current.focus();}}>Focus the input</button>
</>
)
}
};
```
阅读全文
相关推荐

















