All files / src/menu MenuItem.tsx

81.82% Statements 9/11
90% Branches 9/10
66.67% Functions 2/3
80% Lines 8/10

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 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100                                                                              2x 23x                     26x       26x         26x 3x     26x                                       26x                              
import React from "react";
import classNames from "classnames";
import { StyledProps } from "../_type";
import { callBoth } from "../_util/call-both";
import { useConfig } from "../_util/config-context";
 
export interface MenuItemProps extends StyledProps {
  /**
   * 标题
   */
  title?: React.ReactNode;
 
  /**
   * 菜单折叠后标题处显示的图标 URL
   *
   * **传递一组 URL 时,第一个 URL 会作为未激活态图标,第二个 URL 会作为激活态图标**
   */
  icon?: [string, string] | string;
 
  /**
   * 是否为选中状态
   *
   * @default false
   */
  selected?: boolean;
 
  /**
   * 点击回调
   */
  onClick?: (event: React.MouseEvent) => void;
 
  /**
   * 自定义渲染
   *
   * @default children => <a>{children}</a>
   */
  render?: (children: JSX.Element) => JSX.Element;
}
 
const noop = () => {};
const defaultRender = children => <a>{children}</a>;
 
export function MenuItem({
  title,
  icon,
  selected,
  className,
  style,
  onClick = noop,
  render = defaultRender,
}: MenuItemProps) {
  const { classPrefix } = useConfig();
  let defaultIcon;
  let activeIcon;
 
  Iif (typeof icon === "string") {
    defaultIcon = icon;
    activeIcon = icon;
  }
 
  if (Array.isArray(icon)) {
    [defaultIcon, activeIcon] = icon;
  }
 
  const children = render(
    <>
      {defaultIcon && (
        <img
          className={`${classPrefix}-menu__list-icon`}
          src={defaultIcon}
          alt="icon"
        />
      )}
      {activeIcon && (
        <img
          className={`${classPrefix}-menu__list-icon is-selected`}
          src={activeIcon}
          alt="icon"
        />
      )}
      <div className={`${classPrefix}-menu__text`}>{title}</div>
    </>
  );
 
  return (
    <li
      className={classNames(className, { "is-selected": selected })}
      style={style}
    >
      {React.cloneElement(children, {
        className: classNames(
          `${classPrefix}-menu__item`,
          children.props.className
        ),
        onClick: callBoth(onClick, children.props.onClick),
      })}
    </li>
  );
}