Skip to content

12.实现forwardRef为函数组件提供ref的能力

具体代码演化过程请观看视频,这里呈现关键代码:

js
  // react.js
  function forwardRef(render) {
    return {
      $$typeof: REACT_FORWARD_REF,
      render
    }
  }
  const React = {
    forwardRef /////
  }
js
//utils.js
export const REACT_FORWARD_REF = Symbol('react.element')
js
// react-dom.js
import { REACT_ELEMENT, REACT_FORWARD_REF } from './utils'
if (type && type.$$typeof === REACT_FORWARD_REF) {
    return getDomByRefForwardFunction(VNode);
}
function getDomByRefForwardFunction(vNode){
    let { type, props, ref } = vNode;
    let renderVdom = type.render(props, ref);
    if (!renderVdom) return null;
    return createDOM(renderVdom);
}

基于 VitePress 构建