React报错Function components cannot have string refs

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

React报错Function components cannot have string refs

chuck   2022-12-16 我要评论

总览

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

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

// 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对象。

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们