记一次 Ant Design Menu组件的使用与深刻

1. 需求

最近项目中要修改原有的菜单,项目UI为antd,antd的导航菜单长这样:前端

看着挺好的,完美对齐,可是当把个人菜单文案填入以后发现:node

左右不对齐,这也太丑了吧,这要是听任无论要被怼的。react

2. 排查问题

开始审查元素,先查看官方demo正常能对齐的样式:git

再看下个人demo不能对齐的样式:github

发现个人菜单里少了一个 min-width ,也就是说antd在某一步给官方的demo添加了style属性,而没有给个人菜单添加。chrome

为何不给个人加!!!?api

直接来吧,先来一个MutationObserver,详情看MDN文档。浏览器

你是否是想在 antd 给那个 ul 标签添加 style="min-width" 的时候告诉你一下?甚至能打个断点来调试下,但不知道怎么操做?直接上代码:bash

var ele = document.getElementById('item_2$Menu')   // 先找出该元素
var config = {attributes: true, attributeFilter: ['style']}
var callback = function (mutationsList) {
  console.log(mutationsList)
}
var observer = new window.MutationObserver(callback)
observer.observe(ele, config)
复制代码

上面这段代码就是说,在 item_2$Menustyle 属性发生变化的时候,打印下 mutationsList 。因而在我将鼠标移入菜单的时候,打印了如下内容:antd

这有什么用呢?别急,说明鼠标移入,会执行到这里的代码,那么,不如打个断点?

鼠标移入时,浏览器停在了断点上,右边的 call stack 调用栈显示正在执行 callback 函数,看它的下面 adjustWith ,也就是说代码先执行 adjustWith ,而后触发了咱们的断点。咱们接着点开 adjustWith ,发现如下代码:

看来就是这段代码致使的。在浏览器中查看不方便,都是编译以后的代码,转战 Vscode ,查看咱们的node_modules目录,先找到这个文件 node-modules/rc-menu/es/SubMenu.jsadjustWidth 方法:

this.adjustWidth = function () {
  /* istanbul ignore if */
  if (!_this3.subMenuTitle || !_this3.menuInstance) {
    return;
  }
  var popupMenu = ReactDOM.findDOMNode(_this3.menuInstance);
  if (popupMenu.offsetWidth >= _this3.subMenuTitle.offsetWidth) {
    return;
  }

  /* istanbul ignore next */
  popupMenu.style.minWidth = _this3.subMenuTitle.offsetWidth + 'px';
};
复制代码

原来它会先判断宽度,若是 popupMenu 的宽度大于父级的 Title 宽度,就会直接返回,小于的时候才会加上 min-width 属性。

这么费劲总算找到了!

可是,找到了而后呢?问题是我咋去对齐?既然文案长度不一致,那么居中对齐好了。

3. 解决

继续查看 antd 的文档,看看有没有什么参数方法遗漏了,发现个Menu文档小角落有个 More options in rc-menu ,点进去以后发现了一片更广阔的世界 ( 其实我以前就问过同事知道antd还依赖于 react-component ,这个库才是antd组件具体的实现 ) 。

通过一番查找,找到一个props叫作 builtinPlacements 很可疑,描述是 Describes how the popup menus should be positioned(描述popup的菜单如何被定位) ,参数为 dom-align 的配置对象,继续查看 dom-align介绍 发现这就是一个处理定位的小库,处理 domA(sourceNode) 和 domB(targetNode) 的位置关系:

const alignConfig = {
  points: ['tl', 'tr'],        // align top left point of sourceNode with top right point of targetNode
  offset: [10, 20],            // the offset sourceNode by 10px in x and 20px in y,
  targetOffset: ['30%','40%'], // the offset targetNode by 30% of targetNode width in x and 40% of targetNode height in y,
  overflow: { adjustX: true, adjustY: true }, // auto adjust position when sourceNode is overflowed
};

domAlign(domA, domB, alignConfig);
复制代码

这样,就能让domA的 左上角(tl) 和domB的 右上角(tr) 对齐。直觉告诉我 builtinPlacements 属性能解决个人对齐问题。

接下来继续调试,先介绍个调试工具 (同事告诉个人) 。想一想,以前我要调试前端代码都是一堆的 console.log ,要么在浏览器 source 中打断点调试,也能够调试 node_modules 里面的代码(也是从同事那里学来的),可是缺点是代码都是被编译打包过的,可读性很差。因而有 Vscode 的插件 Debugger for Chrome,有了这个插件以后,能够直接在 Vscode 里面给前端js代码打断点!。

接下来可能比较跳跃:

直接找到node_modules下的 rc-menu/es/submenu 目录,就是react-component下的menu组件。先搜索文件夹内搜索 builtinPlacements 这个词,看下哪几个地方用到了。发现以下:

  1. rc-menu/es/submenu.js
...
var builtinPlacements = props.builtinPlacements;
...
React.createElement(
    Trigger,
    {
        ...
        builtinPlacements: _extends({}, placements, builtinPlacements),
        ...
    }
复制代码

原来Submenu拿到传入的 builtinPlacements 用来建立 Trigger 了,继续找 Trigger 发现:

  1. rc-trigger/es/index.js
Trigger.prototype.getPopupAlign = function getPopupAlign() {
    ...
    var builtinPlacements = props.builtinPlacements;
    ...
    return getAlignFromPlacement(builtinPlacements, popupPlacement, popupAlign)
};

...
var align = _this5.getPopupAlign();
...
return React.createElement(
      Popup,
      _extends({
        align: align,
    })
)
复制代码

得,又拿来建立 Popup 了,不过先记住这个函数 getAlignFromPlacement(builtinPlacements, prefixCls, align, alignPoint):

  1. rc-trigger/es/Popup.js
import Align from 'rc-align';
...
React.createElement(
  Align,
  {
    ...
    align: align
    ...
  },
}
复制代码

拿去建立 Align 了:

  1. rc-align/es/Align.js
import { alignElement, alignPoint } from 'dom-align';  // 你总算出来了
...

var align = _this$props.align
...
if (element) {
  result = alignElement(source, element, align);
} else if (point) {
  result = alignPoint(source, point, align);
}
...
复制代码

因此大概关系是 Antd Menu => rc-menu => rc-trigger => rc-align => dom-align ...

其中你在 Menu 传入的 builtinPlacements 参数,会在rc-trigger中被当作参数传入 getAlignPopupClassName(builtinPlacements, prefixCls, align, alignPoint) ,获得的结果最终会被传入到 dom-alignalignElement 或者 alignPoint 中。

可是 builtinPlacements 这个参数怎么传值呢?

  1. function getAlignFromPlacement()

也就是说咱们须要传入相似这样的对象:

builtinPlacements: {
    bottomLeft: {
        // alignConfig对象
        points: ['tl', 'tr'],
        offset: [10, 20],
        ...
    },
    leftTop: {
        ...
    }
}
复制代码

而且可知: getAlignFromPlacement(builtinPlacements, placementStr, align) 中的 placementStr 此时为 bottomLeft ,因此咱们的Menu变成了:

<Menu builtinPlacements={
    {
        bottomLeft: 
        {
            points: ['tc', 'bc'], // 子菜单的 "上中" 和 对应菜单的title "下中" 对齐。
            overflow: {
              adjustX: 1,
              adjustY: 1
            },
            offset: [0, 5]
        }
    }
}>
{this.renderMenuItems(menuItems)}
</Menu>
复制代码

至于 placementStr 的值 bottomLeft ,实际上是:

rc-menu/es/SubMenu.js

var popupPlacementMap = {
  horizontal: 'bottomLeft',
  vertical: 'rightTop',
  'vertical-left': 'rightTop',
  'vertical-right': 'leftTop'
};

var popupPlacement = popupPlacementMap[props.mode];
// 这个值最终做为"placementStr"的值,水平菜单Menu的"mode""horizontal"时,"placementStr"即为"bottomLeft"复制代码

bottomLeft , rightTop 的具体位置图我猜能够参考Antd的 Popconfirm

最终效果图:

4. 总结

本文针对工做中的遇到的一个菜单组件对齐问题,粗略讲到了调试思路,antd组件结构,dom-align, MutationObserver 和 Debuggr for Chrome插件,涉及代码并不复杂, 但愿读者看完能有些许收获。

感谢我那些无所不知的同事们。

相关文章
相关标签/搜索