React中refs的使用是怎样,适用范围有哪些
Admin 2022-10-28 群英技术资讯 520 次浏览
在这篇文章中我们来了解一下“React中refs的使用是怎样,适用范围有哪些”,一些朋友可能会遇到这方面的问题,对此在下文小编向大家来讲解,内容详细,易于理解,希望大家阅读完这篇能有收获哦,有需要的朋友就往下看吧!
React文档中再三强调,请不要过度使用refs,所以当我们可以用dom原生对象解决时,尽量不要使用refs 依照之前的写法,首先是给出类组件和函数组件中refs的写法
在类中,refs有三种方式,目前最常用的是回调的形式使用,分别进行演示
?//直接定义refs,已废弃 class App extends React.PureComponent{ changeInput = ()=>{ const {input} = this .refs } render() { return ( <div> <input type= "text" placeholder={ "please input your value" } onBlur={ this .changeInput} ref={ "input" }/> </div> ) } } //用回调的形式使用 class App extends React.PureComponent{ changeInput = ()=>{ console.log( this .inputRef); } render() { return ( <div> <input type= "text" placeholder={ "please input your value" } onBlur={ this .changeInput} ref={(el)=>{ this .inputRef = el}}/> </div> ) } } //用createRef class App extends React.PureComponent{ inputRef = React.createRef() changeInput = ()=>{ console.log( this .inputRef.current); } render() { return ( <div> <input type= "text" placeholder={ "please input your value" } onBlur={ this .changeInput} ref={ this .inputRef}/> </div> ) } } |
以上就是类组件的三种Ref的写法
1 2 3 4 5 6 7 8 | function App(){ const inputRef = useRef( "" ) return ( <div> <input type= "text" placeholder={ "please input your value" } ref={inputRef}/> </div> ) } |
用一个useRef直接就完成了代码
Refs 是 React 提供给我们的安全访问 DOM 元素或者某个组件实例的句柄。在类组件中,React将ref属性中第一个参数作为DOM中的句柄。而函数组件中,react用hooks的api useRef也能获得ref(在hooks中也常常用useRef的特性即不随着组件刷新而刷新存储的数据从而写一些不变的量)
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:mmqy2019@163.com进行举报,并提供相关证据,查实之后,将立刻删除涉嫌侵权内容。
猜你喜欢
Cocos Creator 允许你将代码拆分成多个脚本文件,并且让它们相互调用。这个步骤简称为 模块化。
这篇文章主要为大家详细介绍了微信小程序自定义底部弹出框动画,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
实现点击跳转页面的方法:1、给按钮元素绑定click点击事件,指定事件处理函数;2、在事件处理函数中利用“window.location.href”属性实现页面跳转,语法为“window.location.href="指定页面路径";”。
这篇文章主要为大家详细介绍了vue+js实现微信上传图片选择功能,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
这篇文章主要为大家介绍了项目中使用Typescript封装axios的示例过程详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
成为群英会员,开启智能安全云计算之旅
立即注册Copyright © QY Network Company Ltd. All Rights Reserved. 2003-2020 群英 版权所有
增值电信经营许可证 : B1.B2-20140078 粤ICP备09006778号 域名注册商资质 粤 D3.1-20240008