首页 > 其他分享 >React报错之Function components cannot have string refs

React报错之Function components cannot have string refs

时间:2022-12-12 22:11:17浏览次数:51  
标签:Function useRef string 钩子 App refContainer current 报错 ref

总览

当我们在一个函数组件中使用一个字符串作为ref时,会产生"Function components cannot have string refs"错误。为了解决该错误,使用useRef()钩子来得到一个可变的ref对象,这样你就可以在组件中作为ref使用。

function-components-cannot-have-string-refs.png

这里有个示例用来展示错误是如何发生的。

// App.js

export default function App() {
  // A string ref has been found within a strict mode tree.
  // ⛔️ Function components cannot have string refs.
  // We recommend using useRef() instead.
  return (
    <div>
      <input type="text" id="message" ref="msg" />
    </div>
  );
}

上述代码片段的问题在于,我们使用了字符串作为ref

useRef

为了解决该错误,使用useRef钩子来获取可变的ref对象。

// App.js

import {useEffect, useRef} from 'react';

export default function App() {
  const refContainer = useRef(null);

  useEffect(() => {
    // 

标签:Function,useRef,string,钩子,App,refContainer,current,报错,ref
From: https://www.cnblogs.com/chuckQu/p/16977261.html

相关文章