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

React中如何从父组件访问类组件内部元素的属性?

解决React类组件内部元素的Ref访问问题

当你将ref直接传递给类组件<Input ref={inputRef} />时,inputRef.current指向的是Input类组件的实例,而非内部的原生input元素,因此直接访问inputRef.current.value会返回undefined。

下面给出两种可行的解决方案:

方案一:使用Ref转发(推荐)

通过React.forwardRef将父组件的ref直接转发到内部的原生input元素上,这种方式更符合React的设计规范。

如果将Input改为函数组件,实现如下:

const Input = React.forwardRef((props, ref) => {
  return <input ref={ref} value="123" />;
});

function App() {
  const inputRef = React.useRef();

  const getValue = () => {
    console.log(inputRef.current.value); // 输出 123
  };

  return (
    <div>
      <Input ref={inputRef} />
      <button onClick={getValue}>获取输入框值</button>
    </div>
  );
}

如果需要保留Input为类组件,可以通过自定义props传递ref:

class Input extends React.Component {
  render() {
    return <input ref={this.props.inputRef} value="123" />;
  }
}

function App() {
  const inputRef = React.useRef();

  const getValue = () => {
    console.log(inputRef.current.value); // 输出 123
  };

  return (
    <div>
      <Input inputRef={inputRef} />
      <button onClick={getValue}>获取输入框值</button>
    </div>
  );
}

方案二:在类组件中暴露内部元素引用

在Input类组件内部创建原生input的ref,然后通过实例方法或直接暴露该ref,让父组件可以访问内部元素的属性。

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

  // 暴露方法供父组件调用获取值
  getInputValue() {
    return this.innerInputRef.current.value;
  }

  render() {
    return <input ref={this.innerInputRef} value="123" />;
  }
}

function App() {
  const inputRef = React.useRef();

  const getValue = () => {
    // 调用类组件实例的方法获取值
    console.log(inputRef.current.getInputValue()); // 输出 123
    // 或者直接访问实例上的内部ref
    console.log(inputRef.current.innerInputRef.current.value); // 输出 123
  };

  return (
    <div>
      <Input ref={inputRef} />
      <button onClick={getValue}>获取输入框值</button>
    </div>
  );
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.23 04:39:26