当前位置:   article > 正文

react hook: useRef

react hook: useRef

在组件顶层调用 useRef 以声明一个 ref
const ref = useRef(initialValue)
console.log(ref.current)
initialValue:ref 对象的 current 属性的初始值。可以是任意类型的值。这个参数在首次渲染后被忽略。
current 返回一个只有一个属性的对象, 初始值为传递的 initialValue。

可以修改 ref.current 属性。与 state 不同,它是可变的。然而,如果它持有一个用于渲染的对象(例如 state 的一部分),那么就不应该修改这个对象。

改变 ref.current 属性时,React 不会重新渲染组件。

useRef 可以保存 DOM 节点的引用

import { useRef } from 'react';

function MyComponent() {
  const inputRef = useRef(null);
  
// ...
  return <input ref={inputRef} />;

function handleClick() {
    inputRef.current.focus();
  }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

useRef 也可以保存任何可变的数据,而不用触发组件的重新渲染

// 可以记录定时器id实现防抖
function handleStartClick() {
  const intervalId = setInterval(() => {
    // ...
  }, 1000);
  intervalRef.current = intervalId;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

useRef 也可以访问子组件的实例

父组件
import React, { useRef } from 'react';
import ChildComponent from './ChildComponent';
const ParentComponent = () => {
  const childRef = useRef();

  const handleClick = () => {
    childRef.current.focusInput();
  };

  return (
    <div>
      <ChildComponent ref={childRef} />
      <button onClick={handleClick}>Focus Input</button>
    </div>
  );
};

export default ParentComponent;

子组件
import React, { forwardRef, useImperativeHandle, useRef } from 'react';

const ChildComponent = forwardRef((props, ref) => {
  const inputRef = useRef(null);

  useImperativeHandle(ref, () => ({
    focusInput() {
      inputRef.current.focus();
    }
  }));

  return <input ref={inputRef} type="text" />;
});

export default ChildComponent;

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37

useRef 也可以useRef 来保存上一次的值,供下次渲染时进行比较或其他操作

不要在渲染期间写入或者读取 ref.current。

function MyComponent() {
  // ...
  // 
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/很楠不爱3/article/detail/297603?site
推荐阅读
相关标签