refs是React中用来取得某个JSX组件或者某个DOM中的一些状态值的时候,用来获取节点的方法。在React官方的解释中,它的适用范围如下:
- 管理焦点,文本选择或媒体播放。
- 触发强制动画。
- 集成第三方 DOM 库。
React文档中再三强调,请不要过度使用refs,所以当我们可以用dom原生对象解决时,尽量不要使用refs 依照之前的写法,首先是给出类组件和函数组件中refs的写法
类组件
在类中,refs有三种方式,目前最常用的是回调的形式使用,分别进行演示
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 | //直接定义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直接就完成了代码
面试常问:React中的refs作用是什么?
Refs 是 React 提供给我们的安全访问 DOM 元素或者某个组件实例的句柄。在类组件中,React将ref属性中第一个参数作为DOM中的句柄。而函数组件中,react用hooks的api useRef也能获得ref(在hooks中也常常用useRef的特性即不随着组件刷新而刷新存储的数据从而写一些不变的量)
以上就是React三大属性之Refs的使用详解的详细内容,更多关于React三大属性之Refs的资料请关注自学编程网其它相关文章!
- 本文固定链接: https://zxbcw.cn/post/209683/
- 转载请注明:必须在正文中标注并保留原文链接
- QQ群: PHP高手阵营官方总群(344148542)
- QQ群: Yii2.0开发(304864863)