React Hooks 之 useRef

66 阅读1分钟

Ref 和 useRef

ref 可以由 useRef 或 createRef 函数创建。

ref 用于引用 DOM元素 / 组件,或数据

使用(DOM元素 / 组件)

  1. ref 用于引用 DOM元素

    DOM元素是对象,ref可直接引用。

import { useRef, useState } from 'react';
function Parent() {
  const inputRef = useRef(null);
  useEffect(()=>{
    inputRef.current.focus();
  })
  return (
    <div>
      <input type="text" ref={inputRef} />
    </div>
  );
}
  1. ref 用于引用 组件
  • 组件是Class组件

    ref可直接引用Class组件的实例化对象。

import { useRef, useState } from 'react';
import ClassComponent from '@components/ClassComponent'
function Parent() {
  const cRef = useRef(null);
  return (
    <div>
      <ClassComponent ref={cRef} />
    </div>
  );
}
  • 组件是函数式组件

    函数组件没有实例,ref直接引用无效,需在FunctionalComponent 组件中使用 forwardRefuseImperativeHandle

import {useRef, useEffect, forwardRef, useImperativeHandle} from ‘react’;
const FunctionalComponent = forwardRef((props, ref) => {
  useImperativeHandle(ref, () => ({ 
    focus: () => {
      inputRef.current.focus() 
    }
  }))
  return ( <input ref={inputRef} /> ) 
})
const myComponent = () => { 
  const fRef = useRef()
  useEffect(()=>{ 
    fRef.current.focus() 
  })
  return ( 
    <FunctionalComponent ref={fRef} />
  ) 
}

使用(数据)

用于在组件中存储信息,且这些信息变更不会触发重新render。

import { useRef } from 'react';

export default function Counter() {
  let ref = useRef(0);

  function handleClick() {
    ref.current = ref.current + 1;
    alert('You clicked ' + ref.current + ' times!');
  }

  return (
    <button onClick={handleClick}>
      Click me!
    </button>
  );
}
  • 变量用useRef和定义在组件最前面的区别
    • useRef 是定义在实例基础上的,如果代码中有多个相同的组件,每个组件的 ref 只跟组件本身有关,跟其他组件的 ref 没有关系。

    • 组件前定义的 global 变量,是属于全局的。如果代码中有多个相同的组件,那这个 global 变量在全局是同一个,他们会互相影响。

import React, { useRef } from "react";

let myConstant = null;

const GlobalConstantExample = ({ index }) => {
  myConstant = index;
  return (
    <div onClick={()=>{
      console.log(myConstant)
    }}
    >
      {`点击Global${index}`}
    </div>
  );
};

const RefExample = ({ index }) => {
  const myConstant = useRef(index);
  return (
    <div onClick={() => {
      console.log(myConstant.current);
        }}
    >
      {`点击Ref${index}`}
    </div>
  );
};

export default function App() {
  return (
    <div>
      <h1>测试组件全局变量</h1>
      <RefExample index={1} />
      <RefExample index={2} />
      <RefExample index={3} />
      <GlobalConstantExample index={4} />
      <GlobalConstantExample index={5} />
      <GlobalConstantExample index={6} />
    </div>
  )
}