# 类型错误：无法读取 null 的属性（读取 'current'）

- **ID:** `react/ref-object-not-initialized`
- **领域:** react
- **类别:** runtime_error
- **验证级别:** ai_generated
- **修复率:** 87%

## 根因

尝试访问 null 的 ref 上的 .current 属性，通常是因为 useRef() 调用时没有初始值，或者 ref 未正确附加到 DOM 元素。

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| React 16.8+ | active | — | — |
| React 17.0.2 | active | — | — |
| React 18.2.0 | active | — | — |

## 解决方案

1. ```
   Ensure the ref is attached to a DOM element: const myRef = useRef(null); return <div ref={myRef}>...</div>. Then access myRef.current only after the component mounts, e.g., inside useEffect or an event handler.
   ```
2. ```
   If using forwardRef, make sure the child component forwards the ref to a DOM element: const Child = forwardRef((props, ref) => <input ref={ref} />);
   ```

## 无效尝试

- **Setting useRef(null) explicitly** — If the ref is not attached to a DOM element, it remains null. The fix is to attach it, not to change the initial value. (40% 失败率)
- **Using useEffect to check if ref.current exists** — A null check only masks the error; the underlying issue (ref not attached) persists. (50% 失败率)
- **Using createRef() instead of useRef()** — createRef() returns { current: null } in function components and will not persist across renders; it's for class components. (60% 失败率)
