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

React类组件Ref问题:父组件调用focusInput方法报错

React类组件Ref调用子组件方法报错:focusInput is not defined

问题场景

使用React类组件时,父组件通过Ref调用子组件的focusInput方法,点击按钮触发clickHandler时抛出错误:Error: focusInput is not defined...

核心错误原因及修复方案

1. 未正确初始化与绑定Ref

类组件中必须通过React.createRef()创建Ref实例,并将其绑定到子组件上,才能通过current属性访问子组件实例:

class Parent extends React.Component {
  constructor(props) {
    super(props);
    // 创建Ref实例
    this.childRef = React.createRef();
  }

  clickHandler = () => {
    // 通过current访问子组件实例,再调用方法
    this.childRef.current.focusInput();
  }

  render() {
    return (
      <div>
        <button onClick={this.clickHandler}>聚焦子组件输入框</button>
        {/* 将Ref绑定到子组件 */}
        <Child ref={this.childRef} />
      </div>
    );
  }
}

2. 子组件未正确暴露实例方法

确保focusInput是子组件的实例方法,而非组件内部的局部函数:

class Child extends React.Component {
  constructor(props) {
    super(props);
    this.inputRef = React.createRef();
  }

  // 定义为类的实例方法,允许父组件通过Ref访问
  focusInput = () => {
    this.inputRef.current.focus();
  }

  render() {
    return <input ref={this.inputRef} />;
  }
}

3. 子组件为函数组件时需转发Ref

如果子组件是函数组件,默认无法直接使用Ref,需通过React.forwardRef转发Ref,并配合useImperativeHandle暴露方法:

const Child = React.forwardRef((props, ref) => {
  const inputRef = React.useRef();
  
  // 向父组件暴露指定方法
  React.useImperativeHandle(ref, () => ({
    focusInput: () => {
      inputRef.current.focus();
    }
  }));

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

关键Ref概念梳理

  • 类组件中,createRef()创建的Ref会在组件挂载后,将子组件实例赋值给current属性
  • 父组件只能通过ref.current访问子组件的实例方法/属性
  • 函数组件本身没有实例,必须通过forwardRef+useImperativeHandle实现Ref转发与方法暴露

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 19:25:04