当我在 React js 中使用 forwardRef 将 Ref 从函数组件传递到其他函数组件时出现 TypeError,

Posted

技术标签:

【中文标题】当我在 React js 中使用 forwardRef 将 Ref 从函数组件传递到其他函数组件时出现 TypeError,【英文标题】:Getting TypeError when I'm passing a Ref from a function component to other function component using forwardRef in react js, 【发布时间】:2021-10-10 20:44:06 【问题描述】:

我想将 App 中的 ref 传递给 Foo,App 和 Foo 是函数组件,所以我使用 forwardRef() 来扭曲 Foo,但我收到错误警告 TypeError: Cannot add property current, object is not extensible。下面是我的代码,我需要更改吗?

import './App.css';
import React,  useState, Component, useEffect, createRef, useRef, forwardRef  from 'react'
import ReactDOM from 'react-dom'

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 = createRef()
  const clicked = () => 
    inputRef.current.focus()
  
  return (
    <div>
      <Foo ref=inputRef />
      <button onClick= clicked >Click Foo</button>
    </div>
  )
  

export default App;

【问题讨论】:

【参考方案1】:

请在启动函数中定义 ref

const inputRef = useRef(null); 

【讨论】:

【参考方案2】:

Ref Forwarding 接收两个参数 props 和 ref。

React.forwardRef((props, ref) =>
    return(
        <button ref=ref>props.children</button>
    )
;

这是您编辑后的代码,我为 ref 添加了 HTMLInputElement 类型。

type RefType = htmlInputElement | null;
interface PropsType 

const Foo = forwardRef<RefType, PropsType>((props, ref) => 
  const onClick = () => 
   if (ref && "current" in ref) 
    ref.current?.focus();
   
;
  return (
     <div>
       <input type="text" ref=ref></input>
       <button onClick=onClick>Focus</button>
     </div>
 );
);

 function App() 
  const inputRef = createRef<HTMLInputElement>();
  const clicked = () => 
  inputRef.current?.focus();
 ;
  return (
     <div>
     <Foo ref=inputRef />
     <button onClick=clicked>Click Foo</button>
    </div>
   );
  
 export default App;

【讨论】:

这里是您的代码的代码沙箱。 codesandbox.io/s/crazy-browser-u7ylg?file=/src/App.tsx

以上是关于当我在 React js 中使用 forwardRef 将 Ref 从函数组件传递到其他函数组件时出现 TypeError,的主要内容,如果未能解决你的问题,请参考以下文章