ref三种使用方法

ref

- 给子元素绑定ref属性,这样父元素就能得到绑定了ref属性的元素/组件
- refs获取  得到的是一个集合
- refs要通过事件或者生命周期获取
    // 方法一: 字符串 (废弃)
    showRef=()=>{
     
        console.log(this.refs)
        //得到的是所有绑定了ref的元素/组件
    }
    render() {
     
        return (
            <div>
                父组件
                <button onClick={
     this.showRef}>获取ref</button>
                <Mother ref='mother' ></Mother>
            </div>
        )
    }    
    // 方法二
    import React, {
      Component,createRef } from 'react'

    btn=createRef()
    showRef=()=>{
     
        // 输出ref 键名为current
        console.log(this.btn)
    }

    render() {
     
        return (
            <div>
                <button onClick={
     this.showRef}>获取ref</button>
                <Mother ref={
     this.btn} ></Mother>
            </div>
        )
    }
//方法三:
    change=()=>{
     
        console.log(this.inp)
    }

    render() {
     
        return (
            <div>
                <input 
                type='text' 
                onChange={
     this.change} 
                ref={
     inp=>{
     this.inp=inp}}/>
            </div>
            //参数inp为当前标签dom元素,this指向组件
        )
    }

你可能感兴趣的:(ref三种使用方法)