【问题标题】:How to add attribute to parent div with ClassName in ReactJS?如何在 ReactJS 中使用 ClassName 向父 div 添加属性?
【发布时间】:2021-11-25 10:07:52
【问题描述】:

我正在使用 ReactJS 材质 UI tabs navigation。我想在一个div 中添加一个名为tabindex 的属性,其中class=MuiTabs-flexContainer MuiTabs-centered 的子节点值为-1。我曾尝试过,但 tabindex=-1 被添加到其他地方:

在此屏幕截图中,我需要 tabindex=-1 在其子节点中,即 button 元素:

这是 UI 选项卡部分:

<Tabs value={value} id="tabSec">
  <Tab
    label={
      <span className={value === 0 ? "active-tab" : "custom-style-on-tab"}>
        ABC
      </span>
    }
  />

  <Tab
    label={
      <span className={value === 1 ? "active-tab" : "custom-style-on-tab"}>
        XYZ
      </span>
    }
  />
</Tabs>;

到目前为止我所做的功能是:

const tabRoving = (element) => {
    element.addEventListener("keydown", function (e) {
      if (e.keyCode === 13) {
        if (element.contains(document.activeElement)) {
          element.childNodes.forEach(function (childElement) {
            if (childElement != document.activeElement) {
              childElement.setAttribute("tabindex", "-1");
              console.log("done");
            } else childElement.setAttribute("tabindex", "0");
          });
        }
      }
    });
  };

  useEffect(() => {
    tabRoving(document.getElementById("tabSec"));
  }, []);

我怎样才能做到这一点?这在带有材质 UI 的 ReactJS 中是否可行?

【问题讨论】:

    标签: javascript html css reactjs jsx


    【解决方案1】:

    您是否尝试过在 Tab 组件上传递 tabIndex={-1} 属性?它应该将未使用的道具向下展开,最终到达按钮。

    Inheritance

    虽然上面没有明确记录,但 ButtonBase 的道具 组件也可在选项卡上使用。您可以利用这一点 定位嵌套组件。

    Spread

    提供给未明确记录的组件的道具是 传播到根元素;例如,className 道具是 应用于根。

    tabIndex 属性传递给Tab 组件:

    <Tabs value={value} id="tabSec">
      <Tab
        tabIndex={-1}
        label={
          <span className={value === 0 ? "active-tab" : "custom-style-on-tab"}>
            ABC
          </span>
        }
      />
    
      <Tab
        tabIndex={-1}
        label={
          <span className={value === 1 ? "active-tab" : "custom-style-on-tab"}>
            XYZ
          </span>
        }
      />
    </Tabs>
    

    【讨论】:

      猜你喜欢
      • 2016-10-01
      • 2015-02-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-05
      • 2015-04-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多