如何在Emotion中无需手动加className实现父hover修改子元素样式?
问题描述
我使用Emotion编写了如下代码:
const styles = { container: css({ display: "flex", justifyContent: "center", alignItems: "center", backgroundColor: "#282c34", padding: "20px", color: "#fff", "&:hover .inner": { backgroundColor: "blue", }, }), inner: css({ margin: "auto", textAlign: "center", backgroundColor: "red", padding: "20px", color: "black", }), }; function App() { return ( <div css={styles.container}> <div css={styles.inner} className="inner"> <h1>Hello World</h1> </div> </div> ); }
我希望在鼠标悬停父容器时修改内部元素的样式,目前需要为内部元素手动添加className,并通过"&:hover .inner"选中它。请问在Emotion中有没有无需手动添加className的更优实现方式?
解决方案
方法1:直接引用子样式生成的类名
Emotion的css函数会返回一个唯一类名,你可以在父样式中直接引用这个类名,无需手动给子元素添加className:
import { css } from '@emotion/react'; // 先定义子元素样式 const innerStyle = css({ margin: "auto", textAlign: "center", backgroundColor: "red", padding: "20px", color: "black", }); // 父样式中通过模板字符串引用子样式的类名 const containerStyle = css({ display: "flex", justifyContent: "center", alignItems: "center", backgroundColor: "#282c34", padding: "20px", color: "#fff", [`&:hover ${innerStyle}`]: { backgroundColor: "blue", }, }); function App() { return ( <div css={containerStyle}> <div css={innerStyle}> <h1>Hello World</h1> </div> </div> ); }
这种方式利用Emotion的类名序列化特性,自动关联父子元素的样式,完全不需要手动维护className。
方法2:使用Styled Components方案
如果项目允许使用Emotion的styled组件,可以更直观地实现样式嵌套控制:
import styled from '@emotion/styled'; // 定义子组件 const Inner = styled.div` margin: auto; text-align: center; background-color: red; padding: 20px; color: black; `; // 父组件中直接通过子组件引用控制悬停样式 const Container = styled.div` display: flex; justify-content: center; align-items: center; background-color: #282c34; padding: 20px; color: #fff; &:hover ${Inner} { backgroundColor: blue; } `; function App() { return ( <Container> <Inner> <h1>Hello World</h1> </Inner> </Container> ); }
这种方式通过组件化的方式管理样式,代码结构更清晰,也完全不需要手动添加className。
内容的提问来源于stack exchange,提问作者Vic
相关产品推荐
相关产品推荐

