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

React函数组件使用forwardRef传递Ref时报TypeError如何解决?

问题修复方案

错误原因

报错是因为forwardRef的传参规则使用错误:forwardRef包裹的渲染函数,第一个参数是接收父组件传递的props对象,第二个参数才是父组件传入的ref实例。你当前把第一个参数当作ref使用,相当于直接在不可修改的props对象上赋值current属性,因此触发了不可扩展对象的报错。

需要修改的内容

  • 调整forwardRef包裹的Foo组件参数顺序,增加props占位参数,把ref放到第二个参数位,无自定义props时可以用_做占位符表示忽略该参数
  • 函数组件内声明ref推荐用useRef代替createRef,createRef多用于类组件,useRef会在组件整个生命周期内保留同一个ref实例,不会随重渲染重置,更符合函数组件的使用需求

修改后完整代码

import './App.css';
import React, { useRef, forwardRef } from 'react'

const Foo = forwardRef((_, inputRef) => {
  const onClick = () => {
    inputRef.current.focus()
  }
  return (
    <div>
      <input type="text" ref={inputRef}></input>
      <button onClick={onClick}>Focus</button>
    </div>
  ) 
})

function App() {
  const inputRef = useRef()
  const clicked = () => {
    inputRef.current.focus()
  }
  return (
    <div>
      <Foo ref={inputRef} />
      <button onClick={clicked}>Click Foo</button>
    </div>
  )
}

export default App;

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.08 22:27:03