All files / src/domref DomRef.tsx

91.3% Statements 21/23
66.67% Branches 4/6
100% Functions 5/5
91.3% Lines 21/23

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64                          271x 271x 271x       273x 273x 273x       271x 271x       544x   544x 544x     544x 544x 988x   988x 62x         926x           544x 544x             59x 544x    
import React, { forwardRef } from "react";
import ReactDOM from "react-dom";
import { mergeRefs } from "../_util/merge-refs";
import { callBoth } from "../_util/call-both";
 
interface DomRefProps {
  children?: React.ReactNode;
}
 
class DomRefInner extends React.Component<
  DomRefProps & { domRef: React.Ref<HTMLElement> }
> {
  public componentDidMount() {
    const dom = ReactDOM.findDOMNode(this) as HTMLElement; // eslint-disable-line react/no-find-dom-node
    const { domRef } = this.props;
    mergeRefs(domRef)(dom);
  }
 
  public componentDidUpdate() {
    const dom = ReactDOM.findDOMNode(this) as HTMLElement; // eslint-disable-line react/no-find-dom-node
    const { domRef } = this.props;
    mergeRefs(domRef)(dom);
  }
 
  public componentWillUnmount() {
    const { domRef } = this.props;
    mergeRefs(domRef)(null);
  }
 
  public render() {
    const { children, domRef, ...props } = this.props;
 
    let childrenElement = children;
    const attachProps = {};
 
    // 元素类型的,可以把要求渲染的 childrenProps 和原本的 props 合并
    Eif (React.isValidElement(childrenElement)) {
      for (const [propName, propValue] of Object.entries(props)) {
        Eif (typeof propValue === "function") {
          // 子节点之前已经有处理函数,则同时调用
          if (childrenElement.props[propName]) {
            attachProps[propName] = callBoth(
              propValue,
              childrenElement.props[propName]
            );
          } else {
            attachProps[propName] = propValue;
          }
        } else {
          attachProps[propName] = propValue;
        }
      }
      childrenElement = React.cloneElement(childrenElement, attachProps);
      return childrenElement;
    }
 
    return children;
  }
}
 
export const DomRef = forwardRef<HTMLElement, DomRefProps>((props, ref) => (
  <DomRefInner {...props} domRef={ref} />
));