在不同组件中创建(悬停)规则时,如何引用另一个组件的样式化组件生成的类名?

How do I reference another component's styled-components generated className while creating a (hover) rule in a different component?

我正在创建一个带有样式组件和 React 的菜单,并希望图标的颜色在悬停时发生变化,但我需要在悬停图标的父级时更改它,以便将悬停在旁边的文本该图标还会激活图标的悬停样式。这是我用来接近的代码:

import React from 'react';
import styled from 'styled-components';
import { Link } from 'react-router-dom';

import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';

const Menu = styled.div`
  display: flex;
  flex-direction: column;
`;

const LinkContainer = styled.div`
  display: flex;
  flex-direction: row;
`;

const FontAwesomeIconExtended = styled.div`
  flex: 1;

  display: grid;
  place-items: center;
  height: 40px;
  width: 40px;
  padding: 10px 2px;
  border-radius: 10px;
  transition: color 0.5s ease;

  color: ${(props) => (props.$isactive ? '#fff' : '#CBE3EB')};
  background: ${(props) =>
    props.$isactive
      ? 'linear-gradient(96.34deg, #004157 0%, #0090b2 100%)'
      : '#fff'};

  ${LinkContainer}:hover & {
    color: ${(props) => (props.$isactive ? '#fff' : 'green')};
  }                                                 /* Problem occurring here */
`;

const LinkText = styled.div`
  flex: 1 0 100px;
`;

function NavLink({ ...props }) {
  return (
    <Link to={props.path}>
      <LinkContainer $isactive={props.$isactive}>
        <FontAwesomeIconExtended
          $isactive={props.$isactive}
          icon={props.icon}
          size='2x'
          as={FontAwesomeIcon}
        />
        <LinkText $isactive={props.$isactive}>{props.name}</LinkText>
      </LinkContainer>
    </Link>
  );
}

export default function NavMenu() {
  return (
    <Menu>
      <NavLink path='/' name='Home' icon='house' $isactive />
      <NavLink path='/profile' name='Profile' icon='user' />
      <NavLink path='/payments' name='Payments' icon='credit-card-front' />
      <NavLink path='/contracts' name='Contracts' icon='file-contract' />
      <NavLink path='/messages' name='Messages' icon='mail-bulk' />
      <NavLink path='/messages' name='Documents' icon='folders' />
      <NavLink path='/locations' name='Transfer' icon='truck-moving' />
    </Menu>
  );
}

The way you reference another styled component in a later component is very clever,但在这种情况下,当它创建悬停规则时,它会在不考虑不同类型的父容器的情况下创建($isactive === true,或 $isactive === false),所以所有的 LinkContainer 都有两个悬停规则,并使用最后定义的规则。这可以通过将 $isactive 移动到最后一个 NavLink 组件来看到。

Here is a screenshot 的 devtools 显示了我的意思是两个悬停规则没有考虑父 class,只是父的一般类型。

我认为解决方案可能涉及在创建悬停规则时具体说明 LinkContainer 的两种类型 class 名称,但是 that doesn't seem well supported。感谢您的观看。

通过重复 class 名称来提高特异性,使用另一个“&”

${LinkContainer}:hover && {