programing

호버에 다른 스타일 구성 요소 대상 지정

lovejava 2023. 3. 20. 21:12

호버에 다른 스타일 구성 요소 대상 지정

스타일리시 컴포넌트의 허버에 대처하는 가장 좋은 방법은 무엇입니까?저는 버튼을 누르면 드러나는 포장 요소를 가지고 있습니다.

컴포넌트에 몇 가지 상태를 구현하고 속성을 호버로 전환할 수 있지만 스타일 컴포넌트를 사용하여 이 작업을 수행할 수 있는 더 나은 방법이 있는지 궁금합니다.

다음과 같은 것은 동작하지 않지만 이상적입니다.

const Wrapper = styled.div`
  border-radius: 0.25rem;
  overflow: hidden;
  box-shadow: 0 3px 10px -3px rgba(0, 0, 0, 0.25);
  &:not(:last-child) {
    margin-bottom: 2rem;
  }
  &:hover {
    .button {
      display: none;
    }
  }
`

스타일 컴포넌트 v2에서는 다른 스타일 컴포넌트를 보간하여 자동으로 생성된 클래스 이름을 참조할 수 있습니다.이 경우 다음과 같은 작업을 수행할 수 있습니다.

const Wrapper = styled.div`
  &:hover ${Button} {
    display: none;
  }
`

상세한 것에 대하여는, 메뉴얼을 참조해 주세요.

컴포넌트의 순서가 중요합니다.이 방법은 만약의 경우에만 효과가 있을 것이다.Button상/전에 정의되어 있습니다.Wrapper.


v1을 사용하는 경우 커스텀클래스 이름을 사용하여 이 문제를 해결할 수 있습니다.

const Wrapper = styled.div`
  &:hover .my__unique__button__class-asdf123 {
    display: none;
  }
`

<Wrapper>
  <Button className="my__unique__button__class-asdf123" />
</Wrapper>

v2는 v1로부터의 드롭 인 업그레이드이므로 업데이트를 권장합니다만, 이것이 카드에 포함되어 있지 않은 경우는, 좋은 회피책이 됩니다.

mxstbr의 답변과 마찬가지로 보간법을 사용하여 상위 구성요소를 참조할 수도 있습니다.이 루트는 부모 컴포넌트의 자 컴포넌트를 참조하는 것보다 컴포넌트의 스타일을 캡슐화하는 것이 조금 더 효과적이기 때문에 마음에 듭니다.

const Button = styled.button`
  ${Wrapper}:hover & {
    display: none;
  }
`;

이 기능이 언제 도입되었는지는 알 수 없지만 v3부터는 작동합니다.

관련 링크: https://www.styled-components.com/docs/advanced#referring-to-other-components

const ConnectButton = styled(WalletDialogButton)`
  background-color: #105b72;
  border: none;
  margin: 10vh auto;
  width: 250px;

  &:hover {
    background-color: #105b72c2;
  }
  `;

마르코스가 말한대로 효과가 있었어스타일 대신 styled()를 사용하고 있습니다.뭔가

이유는 모르겠지만 node_modules 패키지를 참조하고 있습니다.WalletDialogButton존재한다.

저의 해결책은

const Content = styled.div`
  &:hover + ${ImgPortal} {
    &:after {
      opacity: 1;
    }
  }
`;

이것이 나에게 효과가 있었다.

const NoHoverLine = styled.div`
  a {
    &:hover {
      text-decoration: none;
    }
  }
`

이 솔루션은 나에게 효과가 있었다.

const ContentB = styled.span`
  opacity: 0;

  &:hover {
    opacity: 1;
  }
`

const ContentA = styled.span`
  &:hover ~ ${ContentB} {
    opacity: 1;
  }
`

MUI를 사용하는 경우

다음은 코드 샘플입니다.

...
  parentClass: {
    "&:hover $childClass": {
      display: 'flex'
    }
  },
  childClass: {
    position: "absolute",
    right: 5,
    display: 'none'
  },
...

영향을 줄 구성 요소에 자식 클래스 적용

언급URL : https://stackoverflow.com/questions/41007060/target-another-styled-component-on-hover