You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React中Antd标签页内输入框无法聚焦问题求助

Antd标签页切换时输入框无法聚焦问题修复

问题分析

你的代码存在几个关键问题导致输入框无法聚焦:

  1. 父组件ref未传递给子组件:定义的threadRef没有绑定到ChildComponent上,导致调用focusInput时无法正确获取子组件实例。
  2. 子组件拼写错误:forwardRed是forwardRef的笔误,会导致ref无法正常传递。
  3. 错误使用useState存储DOM元素:用useState存输入框元素会因异步更新导致状态与实际DOM不同步,且你将单个元素存入数组,后续focusableElements[0]的调用逻辑错误。
  4. 父组件代码结构异常:包裹onTabChange和JSX的自执行函数属于冗余代码,会导致组件渲染异常。

修复后的代码

父组件

import { Tabs } from 'antd';
import { useRef } from 'react';
import ChildComponent from './ChildComponent';

const Parent = () => {
  const threadRef = useRef(null);

  const onTabChange = (activeKey) => {
    // Antd Tabs的activeKey默认是字符串类型,需与tab的key对应
    if (activeKey === '1' && threadRef.current) {
      threadRef.current.focusInput();
    }
  };

  return (
    <Tabs
      items={[
        { label: 'tab 1', key: '0', children: <>tab 1</> },
        { label: 'tab 2', key: '1', children: <ChildComponent ref={threadRef} /> },
      ]}
      onChange={onTabChange}
    />
  );
};

export default Parent;

子组件

import { Input } from 'antd';
import { forwardRef, useRef, useImperativeHandle } from 'react';

const ChildComponent = forwardRef((props, ref) => {
  // 直接用useRef存储输入框DOM元素
  const inputRef = useRef(null);

  useImperativeHandle(ref, () => ({
    focusInput: () => {
      if (inputRef.current) {
        // Antd Input是封装组件,原生输入框需通过inputRef.current.input获取
        inputRef.current.input.focus();
        inputRef.current.input.value = '1';
      }
    },
  }));

  return <Input className="input" ref={inputRef} />;
});

export default ChildComponent;

关键修复点说明

  • ref正确传递:父组件将threadRef绑定到ChildComponent,确保能调用子组件暴露的focusInput方法。
  • 用useRef存储DOM元素:避免useState的异步更新问题,同步获取最新的DOM元素。
  • Antd Input的ref处理:Antd的Input是封装组件,原生输入框实例在inputRef.current.input上,需调用该实例的focus()方法才有效。
  • 修正activeKey类型:Antd Tabs的activeKey默认是字符串类型,判断时需用'1'而非数字1。

内容的提问来源于stack exchange,提问作者Vignesh s

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.24 23:22:57