React报错Function components cannot have string refs
总览
当我们在一个函数组件中使用一个字符串作为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
对象。
// App.js import {useEffect, useRef} from 'react'; export default function App() { const refContainer = useRef(null); useEffect(() => { // 👇️ this is reference to input element console.log(refContainer.current); refContainer.current.focus(); }, []); return ( <div> <input type="text" id="message" ref={refContainer} /> </div> ); }
useRef()
钩子可以被传递一个初始值作为参数。该钩子返回一个可变的ref
对象,其.current
属性被初始化为传递的参数。
需要注意的是,我们必须访问ref
对象上的current
属性,以获得对我们设置了ref
属性的input
元素的访问。
当我们传递ref
属性到元素上时,比如说,<input ref={myRef} />
。React将ref
对象上的.current
属性设置为相应的DOM节点。
useRef
钩子创建了一个普通的JavaScript对象,但在每次渲染时都给你相同的ref
对象。换句话说,它几乎是一个带有.current
属性的记忆化对象值。
不会重新渲染
应该注意的是,当你改变ref
的current
属性的值时,不会引起重新渲染。
例如,一个ref
不需要包含在useEffect
钩子的依赖数组中,因为改变它的current
属性不会引起重新渲染。
// App.js import {useEffect, useRef} from 'react'; export default function App() { const refContainer = useRef(null); const refCounter = useRef(0); useEffect(() => { // 👇️ this is reference to input element console.log(refContainer.current); refContainer.current.focus(); // 👇️ incrementing ref value does not cause re-render refCounter.current += 1; console.log(refCounter.current); }, []); return ( <div> <input type="text" id="message" ref={refContainer} /> </div> ); }
例子中的useEffect
钩子只运行了2次,因为useRef
在其内容发生变化时并没有通知我们。
改变对象的current
属性并不会导致重新渲染。
以上就是React报错Function components cannot have string refs的详细内容,更多关于React报错Function components cannot have string refs的资料请关注脚本之家其它相关文章!
相关文章
react-native 封装选择弹出框示例(试用ios&android)
本篇文章主要介绍了react-native 封装选择弹出框示例(试用ios&android),具有一定的参考价值,有兴趣的可以了解一下2017-07-07React组件实例三大核心属性State props Refs详解
组件实例的三大核心属性是:State、Props、Refs。类组件中这三大属性都存在。函数式组件中访问不到 this,也就不存在组件实例这种说法,但由于它的特殊性(函数可以接收参数),所以存在Props这种属性2022-12-12在react-antd中弹出层form内容传递给父组件的操作
这篇文章主要介绍了在react-antd中弹出层form内容传递给父组件的操作,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧2020-10-10
最新评论