React之Ref如何去使用?

简介: React之Ref如何去使用?

ref对象的创建,所谓创建,就是通过React.createRef或者React.useRef来创建一个Ref原始对象。

而react对ref的处理则是,主要指的是对于标签中的ref属性,react是如何处理以及react转发ref。


ref对象的创建


什么是ref对象,ref对象就是用createRef或者useRef创建出来的对象。

{
    current: null // current指向的ref对象获取到的实际内容。可以是dom元素,组件实例,或者是其它
}

react提供两种方法创建ref对象。


  • 类组件:React.createRef


第一种是通过React.createRef 创建一个ref对象。

class Index extends React.Component{
    constructor(props){
        super(props)
        this.currentDom = React.createRef(null)  // 创建ref
    }
    componentDidMount() {
        console.log(this.currentDom)
    }
    render = () => <div ref={this.currentDom}> ref 对象创建获取元素组件</div>
}

函数组件:useRef


第二种是通过函数组件创建Ref,可以用hooks中的useRef来达到同样的效果


export default function Index () {
    const currentDom = React.useRef(null)
    UseEffect(() => {
        console.log(currentDom.current)
    },[])
    return <div ref={currentDom}></div>
}


类组件获取ref的三种方式


ref属性是一个字符串

class Children extends Component{
    render = () => <div>hello,world</div>
}
export default class Index extends React.Component{
    componentDidMount(){
        console.log(this.refs)
    }
    render = () => <div>
        <div ref="currentDom"></div>
        <Children ref="currentComInstance"></Children>
    </div>
}

ref 属性是一个函数

class Children extends React.Component{
    render = () => <div>hello,world</div>
}
export default class Index extends React.component{
    currentDom = null
    currentComponentInstance = null
    componentDidMount () {
        console.log(this.currentDom)
        console.log(this.currentComponentInstance)
    }
     render=()=> <div>
        <div ref={(node)=> this.currentDom = node }  >Ref模式获取元素或组件</div>
        <Children ref={(node) => this.currentComponentInstance = node  }  />
    </div>
}

ref属性是一个ref对象

d164052b0c284f3ab8f3cc78d7b13885.png

相关文章
第八章 react组件实例中三大属性之ref
第八章 react组件实例中三大属性之ref
112 0
学习react基础(3)_setState、state、jsx、使用ref的几种形式
本文探讨了React中this.setState和this.state的区别,以及React的核心概念,包括核心库的使用、JSX语法、类与函数组件的区别、事件处理和ref的使用。
104 3
学习react基础(3)_setState、state、jsx、使用ref的几种形式
react学习(17)回调形式的ref
react学习(17)回调形式的ref
react学习(18)createRef形式的ref
react学习(18)createRef形式的ref
|
8月前
|
react18【系列实用教程】useRef —— 创建 ref 对象,获取 DOM (2024最新版)
react18【系列实用教程】useRef —— 创建 ref 对象,获取 DOM (2024最新版)
92 0
深入了解 React 中的 Ref:不是魔法,是超级工具
深入了解 React 中的 Ref:不是魔法,是超级工具
252 0
React 中的 ref 和 refs:解锁更多可能性(下)
React 中的 ref 和 refs:解锁更多可能性(下)
React 中的 ref 和 refs:解锁更多可能性(下)