React中Antd标签页内输入框无法聚焦问题求助
Antd标签页切换时输入框无法聚焦问题修复
问题分析
你的代码存在几个关键问题导致输入框无法聚焦:
- 父组件ref未传递给子组件:定义的
threadRef没有绑定到ChildComponent上,导致调用focusInput时无法正确获取子组件实例。 - 子组件拼写错误:
forwardRed是forwardRef的笔误,会导致ref无法正常传递。 - 错误使用useState存储DOM元素:用
useState存输入框元素会因异步更新导致状态与实际DOM不同步,且你将单个元素存入数组,后续focusableElements[0]的调用逻辑错误。 - 父组件代码结构异常:包裹
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
相关产品推荐
相关产品推荐

