React 中的 ForwardRef的使用

React 中的 forwardRef Hooks 是指将子组件的 Dom 节点暴露给给父组件,在 React 中如果想要访问 Dom 节点是通过 useRef 这个 hooks,而 forwardHook 在 useRef 做了扩展。useRef 是当前组件中间中的节点,而 forwardRef 相当于做了一层封装将父组件的一个 Ref 对象传到子组件中,如下例:

#父组件中定义 Ref
const ref = useRef(null);

  function handleClick() {
    ref.current.focus();
  }

  return (
    <form>
      <MyInput label="Enter your name:" ref={ref} />
      <button type="button" onClick={handleClick}>
        Edit
      </button>
    </form>
  );
}
#封装子组件,传入 Ref参数
import { forwardRef } from 'react';

const MyInput = forwardRef(function MyInput(props, ref) {
  const { label, ...otherProps } = props;
  return (
    <label>
      {label}
      <input {...otherProps} ref={ref} />
    </label>
  );
});

export default MyInput;

forwardRef 源码中定义一个elementType 为 REACT_FORWARD_REF_TYPE reactElement。
在这里插入图片描述

总结

forwardRef 相当于是为 ref 传递的一种方式,普通的函数式组件就是 Render,而 fowardRef 多加了 Ref 参数。

相关推荐

  1. React.forwardRef 使用

    2024-06-08 22:14:04       24 阅读
  2. react api:forwardRef

    2024-06-08 22:14:04       36 阅读
  3. React hooks - forwardRef+useImperativeHandle

    2024-06-08 22:14:04       32 阅读
  4. reactzustand使用

    2024-06-08 22:14:04       44 阅读
  5. React useReducer使用

    2024-06-08 22:14:04       39 阅读
  6. Reactantd使用技巧

    2024-06-08 22:14:04       51 阅读
  7. react,hooksuseRef使用

    2024-06-08 22:14:04       44 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-06-08 22:14:04       98 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-06-08 22:14:04       106 阅读
  3. 在Django里面运行非项目文件

    2024-06-08 22:14:04       87 阅读
  4. Python语言-面向对象

    2024-06-08 22:14:04       96 阅读

热门阅读

  1. 生物神经网络 原理分析研读01

    2024-06-08 22:14:04       28 阅读
  2. 大模型的 Embedding 模型该如何进行微调?

    2024-06-08 22:14:04       28 阅读
  3. Sass详解

    2024-06-08 22:14:04       32 阅读
  4. AI-知识库搭建(二)GPT-Embedding模型使用

    2024-06-08 22:14:04       32 阅读
  5. SCSS中的结构化伪类选择器详解与示例

    2024-06-08 22:14:04       33 阅读
  6. 基于 PyTorch 的 Python 深度学习:注意力机制

    2024-06-08 22:14:04       28 阅读
  7. linux防止nmap扫描

    2024-06-08 22:14:04       27 阅读
  8. Leetcode 54. 螺旋矩阵(二维数组移动坐标)

    2024-06-08 22:14:04       34 阅读
  9. iperf

    2024-06-08 22:14:04       23 阅读
  10. 爬虫-打包整个小说网站

    2024-06-08 22:14:04       28 阅读
  11. 用Python实现奇怪的疯狂按键需求

    2024-06-08 22:14:04       36 阅读