如何为自定义组件添加 focus 状态?

解读

该问题考察候选人对React组件状态管理及焦点交互机制的理解,需要结合Next.js框架特性进行实现。重点在于如何通过React的事件处理系统与状态管理能力,配合Next.js的页面组件特性,实现组件的聚焦状态控制。在实际开发中,这类需求常见于表单输入、可聚焦的交互元素等场景。

知识点

  1. React组件状态管理(useState/useEffect)
  2. DOM元素焦点控制(ref、focus事件)
  3. Next.js页面组件生命周期
  4. CSS伪类与动态样式绑定
  5. 无障碍访问(a11y)规范

答案

在Next.js中为自定义组件添加focus状态需遵循以下步骤:

  1. 状态声明:使用useState创建焦点状态变量
const [isFocused, setIsFocused] = useState(false);
  1. ref绑定:通过useRef获取DOM元素引用
const inputRef = useRef<HTMLInputElement>(null);
  1. 事件监听:在组件挂载时绑定focus/blur事件
useEffect(() => {
  const handleFocus = () => setIsFocused(true);
  const handleBlur = () => setIsFocused(false);
  
  inputRef.current?.addEventListener('focus', handleFocus);
  inputRef.current?.addEventListener('blur', handleBlur);
  
  return () => {
    inputRef.current?.removeEventListener('focus', handleFocus);
    inputRef.current?.removeEventListener('blur', handleBlur);
  };
}, []);
  1. 样式绑定:通过条件渲染应用focus样式
<div className={`input-container ${isFocused ? 'focused' : ''}`}>
  <input ref={inputRef} type="text" />
</div>
  1. Next.js优化:若组件为动态加载内容,需在useEffect中处理依赖项
useEffect(() => {
  if (someCondition) {
    // 处理动态内容后的焦点逻辑
  }
}, [someCondition]);

拓展思考

在复杂场景中可考虑:

  1. 使用自定义hook封装focus逻辑:
function useFocusHandler(initialValue = false) {
  const [isFocused, setIsFocused] = useState(initialValue);
  const ref = useRef<HTMLInputElement>(null);
  
  useEffect(() => {
    const handleFocus = () => setIsFocused(true);
    const handleBlur = () => setIsFocused(false);
    
    ref.current?.addEventListener('focus', handleFocus);
    ref.current?.addEventListener('blur', handleBlur);
    
    return () => {
      ref.current?.removeEventListener('focus', handleFocus);
      ref.current?.removeEventListener('blur', handleBlur);
    };
  }, []);
  
  return { isFocused, ref };
}
  1. 结合Next.js的动态导入特性实现按需加载组件的焦点控制
  2. 使用react-focus-visible库处理浏览器兼容性问题
  3. 在表单组件中实现复合焦点状态管理(如结合hover、active状态)
  4. 考虑使用CSS变量实现更灵活的样式控制:
.input-container {
  --focus-border: 2px solid #0070f3;
}
.input-container.focused {
  border: var(--focus-border);
}