# TypeError：无法读取 null 的属性（读取 'focus'）

- **ID:** `react/ref-object-null-on-mount`
- **领域:** react
- **类别:** runtime_error
- **验证级别:** ai_generated
- **修复率:** 90%

## 根因

访问 ref 对象时其为 null，因为组件尚未挂载或 ref 错误地附加到了无状态组件。

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| React 18.2.0 | active | — | — |
| React 19.0.0-rc.2 | active | — | — |

## 解决方案

1. ```
   Access the ref inside a useEffect hook with an empty dependency array to ensure the component is mounted: useEffect(() => { if (ref.current) { ref.current.focus(); } }, []);
   ```
2. ```
   Use a callback ref to handle the ref assignment: const inputRef = useCallback(node => { if (node) { node.focus(); } }, []); <input ref={inputRef} />
   ```
3. ```
   If using a function component, wrap it with React.forwardRef and pass the ref to a DOM element inside: const MyComponent = React.forwardRef((props, ref) => <input ref={ref} />);
   ```

## 无效尝试

- **** — The ref is not attached until after the component mounts, so it is null initially. (90% 失败率)
- **** — This creates a dummy element that is not connected to the DOM, so methods like focus() may not work as expected. (70% 失败率)
- **** — Function components cannot receive refs directly; they must be wrapped in forwardRef. (80% 失败率)
