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 参数。

相关推荐
yuanyxh3 小时前
Mac 软件推荐
前端·javascript·程序员
万少3 小时前
AtomCode开发微信小程序《谁去呀》 全流程
前端·javascript·后端
某人辛木3 小时前
Web自动化测试
前端·python·pycharm·pytest
Kagol4 小时前
Superpowers GSD gstack AgentSkills深度测评
前端·人工智能
excel5 小时前
JavaScript 字符串与模板字面量:从表象到本质理解
前端
京东云开发者5 小时前
当AI成为导演-如何用AI创作动漫短剧
前端
李白的天不白6 小时前
使用 SmartAdmin 进行前后端开发
java·前端
乘风gg6 小时前
🤡PUA AI Coding 工具 的 10 条终极语录
前端·ai编程·claude
学Linux的语莫6 小时前
Vue 3 入门教程
前端·javascript·vue.js
怕浪猫6 小时前
第一章、Chrome DevTools Protocol (CDP) 详解
前端·javascript·chrome