# 类型错误：无法读取 null 的属性（读取 'focus'）。此错误位于：MyComponent (at App.js:15)

- **ID:** `react/usecontext-null-focus`
- **领域:** react
- **类别:** runtime_error
- **验证级别:** ai_generated
- **修复率:** 88%

## 根因

ref 附加到条件渲染的组件或元素上，当元素未挂载时（ref.current 为 null），代码尝试调用 ref.current.focus()。

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| react@18.2.0 | active | — | — |
| react-dom@18.2.0 | active | — | — |

## 解决方案

1. ```
   Check if ref.current is not null before calling focus: `if (ref.current) { ref.current.focus(); }`
   ```
2. ```
   Use useEffect with a dependency on the condition that controls rendering: `useEffect(() => { if (isVisible && ref.current) { ref.current.focus(); } }, [isVisible]);`
   ```

## 无效尝试

- **Using optional chaining (ref.current?.focus()) without understanding why ref is null** — Silently fails when the element is not mounted; the focus action never happens, which may be a UX issue. (50% 失败率)
- **Moving the focus call to useEffect with no dependency array** — May run before the element is rendered if the component conditionally renders the element later. (60% 失败率)
- **Using a callback ref and trying to focus immediately** — Callback refs are called during render, but the DOM may not be fully attached yet. (45% 失败率)
