将 class 和 id 添加到 React Fabric UI 数据透视项 headerButtonProps

问题描述

我似乎无法通过 className 中的 id 使用标签按钮链接呈现 headerButtonPropsPivotItem。我认为这应该是可能的,因为 7.114.0 版为枢轴按钮添加IButtonProps ..我错过了一些明显的东西吗?我的数据属性呈现得很好,以及标签内容周围容器元素的类名和 ID。

<PivotItem
  headerText={tab.label}
  itemKey={tab.id}
  key={tab.id}
  headerButtonProps={{
    'data-test': 'test',className: 'tab-button',id: 'tab-id'
  }}
  itemCount={tab.count}
  className={tab.className}
  id={tab.idName}
 >
  {tab.content}
</PivotItem>

解决方法

如果在 PivotPivotItem 组件上的 vs-code 中按 F12,将带您到 node_modules 中的源代码。导航到附近的 Pivot.base.js 文件 - 我认为第 48 行显示了为什么会发生这种情况:

return (React.createElement(CommandButton,tslib_1.__assign({},headerButtonProps,{ id: tabId,key: itemKey,className: isSelected ? _this._classNames.linkIsSelected : _this._classNames.link,onClick: _this._onLinkClick.bind(_this,itemKey),onKeyPress: _this._onKeyPress.bind(_this,ariaLabel: link.ariaLabel,role: "tab","aria-selected": isSelected,name: link.headerText,keytipProps: link.keytipProps,"data-content": contentString }),linkContent));

这是 renderPivotLink 的默认实现 - 您可以看到它从链接参数中获取 headerButtonProps。我假设链接参数派生自 PivotItem 类型的孩子。

#48 行的 tslib_1.__assign() 方法有效地将您传入的 headerButtonProps 与第三个参数中的对象合并,第三个参数同时设置了 id 和 {{1} } - 所以这些值会覆盖你的值。

如果切换这两个参数,您的 className 或 ID 等将替换在 Pivot 源代码中设置的那些参数——他们显然不希望人们这样做,所以这是正确的顺序。他们本可以选择将 className 设置为一个对象,将您的 classNames 与源代码中的 classNames 合并——这就是他们在其他一些组件中所做的——但他们没有在这里这样做。

如果你想建议他们这样做 - 在 repo 上提出问题或拉取请求可能是个好主意: https://github.com/microsoft/fluentui/tree/master/packages/react

我意识到我已经晚了 2 个月才回复您 - 但是,如果您希望根据 ID 或类在 CSS 或 JS/TS 中执行某些操作 - 您仍然可以使用您的数据属性作为选择器。

对于样式表 - 给养育 Pivot 本身一个 className - 示例(SCSS):

className

代码(TS):

.parentPivot {
   button[data-your-attribute="someValue"] {
      /* your styling here */
   }
}

希望对未来有所帮助!

汤姆