2025年【React】三大核心属性refs

【React】三大核心属性refsReact 三大核心属性 refs 1 refs 基本认识 Refs 其实是提供了一个对真实 DOM 组件 的引用 我们可以通过这个引用直接去操作 DOM 组件 2 为什么要用 refs 我们在使用 React 写代码的时候对 Refs 的使用比较少 因为我们很少直接操作底层 DOM 元素

大家好,我是讯享网,很高兴认识大家。

React三大核心属性—refs

1. refs基本认识

Refs其实是提供了一个对真实DOM(组件)的引用,我们可以通过这个引用直接去操作DOM(组件)

2. 为什么要用refs

我们在使用React写代码的时候对Refs的使用比较少,因为我们很少直接操作底层DOM元素,而是通过在render里编写我们的页面结构,再由React来组织DOM元素的更新。

而在少数情况中,有些需求要求我们对页面的真实DOM进行直接操作,这就要求我们有直接访问真实DOM的能力,而Refs就为我们提供了这种能力。

3. 创建ref的三种形式
字符串形式的ref

在官网文档中也标记了过时的API。它已过时并可能会在未来的版本被移除。在render方法中使用字符串定义一个ref:

 <script type="text/babel"> // 定义函数组件 class Demo extends React.Component { 
    showData1 = () => { 
    console.log(this.refs.input1.value); } render() { 
    return ( <div> { 
   /*字符串形式的ref*/} <input ref="input1" type="text" placeholder="点击按钮提示数据" />&nbsp; <button onClick={ 
   this.showData1}>点我提示左侧数据</button>&nbsp; </div> ) } } // 渲染组件到页面 ReactDOM.render(<Demo />, document.querySelector('#test')) </script> 

讯享网
回调函数方式的ref

React 也支持另一种设置 refs 的方式,也就是回调形式的refs。它能使我们更加容易并且精细的控制refs的设置和解除。


讯享网

在ref中,你会传递一个函数。这个函数中接受 React 组件实例或 HTML DOM 元素作为参数,以使它们能在其他地方被存储和访问。

讯享网 <script type="text/babel"> // 定义函数组件 class Demo extends React.Component { 
    showData2 = () => { 
    console.log(this.input2.value); } render() { 
    return ( <div> { 
   /* 回调形式的ref c就是当前节点,把当前节点放到实例对象上*/} <input ref={ 
   c => this.input2 = c} onBlur={ 
   this.showData2} type="text" placeholder="失去焦点提示数据" /> </div> ) } } // 渲染组件到页面 ReactDOM.render(<Demo />, document.querySelector('#test')) </script> 
使用createRef()

createRef 是 React v16.3 新增的API,允许我们访问 DOM 节点或在 render 方法中创建的 React 元素。

Refs 是使用 React.createRef() 创建的,并通过 ref 属性附加到 React 元素。

Refs 通常在 React 组件的构造函数中定义,或者作为函数组件顶层的变量定义,然后附加到 render() 函数中的元素。

 <script type="text/babel"> // 定义函数组件 class Demo extends React.Component { 
    myRef = React.createRef() showData3 = () => { 
    console.log(this.myRef.current.value); } render() { 
    return ( <div> { 
   /* 使用createRef()来创建ref*/} <input ref={ 
   this.myRef} onFocus={ 
   this.showData3} type="text" placeholder="获取焦点提示数据" /> </div> ) } } // 渲染组件到页面 ReactDOM.render(<Demo />, document.querySelector('#test')) </script> 
Refs注意点
  • 不要过度使用Refs,如果可以通过声明实现,则尽量避免使用refs;
  • 不能在函数式组件上使用ref属性(就是function定义的组件,不是class),因为它们没有实例;
  • ref 的更新会发生在componentDidMount 或 componentDidUpdate 生命周期钩子之前。所以不能在组件卸载的时候直接使用ref的react元素,React 会在组件卸载时将ref 改回 null。
小讯
上一篇 2025-04-02 17:30
下一篇 2025-04-02 19:17

相关推荐

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容,请联系我们,一经查实,本站将立刻删除。
如需转载请保留出处:https://51itzy.com/kjqy/107999.html