加入收藏 | 设为首页 | 会员中心 | 我要投稿 银川站长网 (https://www.0951zz.com/)- 云通信、基础存储、云上网络、机器学习、视觉智能!
当前位置: 首页 > 综合聚焦 > 编程要点 > 语言 > 正文

React中refs的运用是怎样 适用范围有哪些

发布时间:2023-09-28 12:38:49 所属栏目:语言 来源:
导读:在这篇文章中我们来了解一下“React中refs的使用是怎样,适用范围有哪些”,一些朋友可能会遇到这方面的问题,对此在下文小编向大家来讲解,内容详细,易于理解,希望大家阅读完这篇能有收获哦,有需要的朋

在这篇文章中我们来了解一下“React中refs的使用是怎样,适用范围有哪些”,一些朋友可能会遇到这方面的问题,对此在下文小编向大家来讲解,内容详细,易于理解,希望大家阅读完这篇能有收获哦,有需要的朋友就往下看吧!

refs是React中用来取得某个JSX组件或者某个DOM中的一些状态值的时候,用来获取节点的方法。在React官方的解释中,它的适用范围如下:

管理焦点,文本选择或媒体播放。

触发强制动画。

集成第三方 DOM 库。

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 8function 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中的句柄。

(编辑:银川站长网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章