使用ref的注意点


获取类组件

import React from 'react'

class Home extends React.Component {
  render() {
    return (
      
我是类组件
) } } class App extends React.Component { constructor(props) { super(props); this.myRef = React.createRef(); } render() { return (
this.myRef} />
) } btnClick() { console.log(this.myRef.current); // 获取的是类组件的实例对象 } } export default App;
  • 使用  ref 获取的是类组件的实例

ref转发

import React from 'react'

const Home = React.forwardRef(function (props, myRef) {
  return (
    
我是函数式组件
) })
class App extends React.Component { constructor(props) { super(props);
this.myRef = React.createRef(); } render() { return (
this.myRef} />
) } btnClick() { console.log(this.myRef.current); } } export default App;
  • 通过 ref 无法直接获取到函数式组件,但可以获取到函数式组件内部的某个DOM
  • 通过  React.createRef 函数创建一个对象,将该对象赋值给函数式组件的  ref 属性
  • 函数式组件需要传递给  React.forwardRef 函数,函数式组件的第二个参数是外界使用时传递进来的  ref 
  • 我们无法直接拿到函数式组件本身,但可以拿到函数式组件当中的某一个元素