What is the best way to handle hovers in styled-components. I have a wrapping element that when hovered will reveal a button.
コンポーネントに何らかの状態を実装し、ホバー時にプロパティを切り替えることはできますが、styled-cmponents を使用してこれを行うより良い方法があるかどうか疑問に思っていました。
次のようなものは機能しませんが、理想的です。
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;
}
}
`
ベストアンサー1
styled-components 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 からのドロップイン アップグレードなので、更新することをお勧めしますが、それが不可能な場合は、これが適切な回避策になります。