首页 > 解决方案 > 未应用 reactjs 应用程序中的 css - 基于位置逻辑的逻辑

问题描述

我正在尝试解决为什么没有将特定的 css 类应用于我的 reactjs 应用程序中的按钮。我似乎找不到错误 - 我确定这是我缺少的一些简单的东西。

这是css定义:

.button-group-right {
    justify-content: flex-end;

    .toolbox-button {
        &:nth-child(2) {
            .toolbox-icon {
                background-color: $hangupColor;
                border: 1px solid $hangupColor;
                width: 40px;
                height: 40px;
        
                &:hover {
                    background-color: $hangupColor;
                }

                svg {
                    fill: #fff;
                }
            }
        }
    }

}

如您所见,如果按钮的索引值为 2,则应该应用此样式。(基本上应用红色背景)

我添加了一个控制台调试语句来打印数组的内容,以证明挂断按钮是索引 2:

(3) ["overflowmenu", "tileview", "hangup"]
0: "overflowmenu"
1: "tileview"
2: "hangup"
length: 3
__proto__: Array(0)

呈现的 HTML 代码如下所示:

<div class="button-group-right">

    (div for first 2 buttons removed for simplifying code review)

    <div aria-label="Leave the call" class="toolbox-button">
        <div>
            <div class="toolbox-icon">
                <div class="jj-icon">
                    <svg height="24" width="24" viewBox="0 0 32 32">
                        <path></path>
                    </svg>
                </div>
            </div>
        </div>
    </div>
</div>

如果你看到我迷路的地方,我会全神贯注。

谢谢。

标签: cssreactjs

解决方案


我想你误解了什么nth-child意思。这与嵌套索引无关,而与父元素中的位置有关。

例如在以下代码中:

<html>
<head>
<style> 
p:nth-child(2) {
  background: red;
}
</style>
</head>
<body>
<div>
<p>The first paragraph.</p>
<p>The second paragraph.</p>
</div>
<p>The third paragraph.</p>
<p>The fourth paragraph.</p>

</body>
</html>

第二个和第三个p将获得红色背景,因为它们是父母second p中的第二个孩子(是 divthird p中的第二个孩子并且是 body 元素的第二个孩子)。

所以如果你想将样式传递给toolbox-icon div你必须这样做:

 .toolbox-button {
            .toolbox-icon {
                background-color: $hangupColor;
                border: 1px solid $hangupColor;
                width: 40px;
                height: 40px;
        
                &:hover {
                    background-color: $hangupColor;
                }

                svg {
                    fill: #fff;
                }
            }
    }

推荐阅读