useRef() 是 React 中的一个 Hook,用于创建可变的 ref 对象,其常见用法如下:
- 创建一个 ref 对象
const myRef = useRef();
- 访问 ref 对象的 current 属性
const myRef = useRef();
// 在组件中访问 ref 对象的 current 属性
console.log(myRef.current);
- 更改 ref 对象的 current 属性
const myRef = useRef();
// 在组件中更改 ref 对象的 current 属性
myRef.current = 'new value';
- 将 ref 对象传递给子组件
const myRef = useRef();
// 在父组件中将 ref 对象传递给子组件
<ChildComponent ref={myRef} />
- 在子组件中访问 ref 对象
// 在子组件中访问父组件传递的 ref 对象
const ChildComponent = React.forwardRef((props, ref) => {
console.log(ref);
return <div>Child Component</div>;
});