天天看点

React之Ref如何去使用?

  1. ref对象的创建,所谓创建,就是通过React.createRef或者React.useRef来创建一个Ref原始对象。
  2. 而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属性是一个字符串
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对象

继续阅读