使用MUI styled函数与Styled Components时如何引用其他样式组件?
问题
在使用MUI的styled函数搭配Styled Components时,我想引用其他样式组件,预期写法如下:
const Parent = styled('div')({ "&:hover": { [`${Child}`]: { color: 'red' } } });
但运行时出现了如下错误:
Component selectors can only be used in conjunction with @emotion/babel-plugin, the swc Emotion plugin, or another Emotion-aware compiler transform.
我已经按照指引安装了@emotion/babel-plugin,并在vite配置文件中做了配置(试过不带参数导入和带参数的方式,都没用),我的vite.config.ts配置如下:
export default defineConfig({ plugins: [ eslint(), react({ babel: { plugins: [ // "@emotion/babel-plugin" [ "@emotion", // "@emotion/babel-plugin", <<<< as an alternative also doesn't work { importMap: { "@mui/material/styles": { styled: { canonicalImport: ["@emotion/styled", "default"], styledBaseImport: ["@mui/material/styles", "styled"] } }, "@mui/system": { styled: { canonicalImport: ["@emotion/styled", "default"], styledBaseImport: ["@mui/system", "styled"] } } } } ] ] }, jsxImportSource: "@emotion/react" }), tsconfigPaths() ], resolve: { alias: { "@mui/styled-engine": "@mui/styled-engine-sc" } }, });
请问要使用这种组件选择器特性,我是不是必须从Styled Components切换到Emotion?
解决方案
是的,你需要切换到Emotion才能使用这种组件选择器特性。
原因很明确:你当前把MUI的样式引擎指定为了Styled Components(通过resolve.alias将@mui/styled-engine指向@mui/styled-engine-sc),但你尝试用的${Child}这种组件选择器语法是Emotion独有的特性,Styled Components本身不支持这种写法——它的语法体系里没有通过模板字符串引用其他组件选择器的机制。
另外你当前的vite配置存在矛盾:一边指定Styled Components作为样式引擎,一边又配置了Emotion的Babel插件和jsxImportSource,这会导致工具链逻辑混乱,也是错误持续出现的原因之一。
如果要保留Styled Components,得换方式实现需求:
- 给子组件传递props,父组件hover时修改props值,子组件根据props切换样式
- 使用CSS类名选择器,给子组件指定类名,在父组件的hover样式里通过类名选中子组件
如果要使用你预期的组件选择器语法,按以下步骤调整:
- 移除
resolve.alias里的@mui/styled-engine配置,让MUI默认使用Emotion作为样式引擎 - 确保安装了必要依赖:
@emotion/react、@emotion/styled、@emotion/babel-plugin - 保留当前vite中Emotion相关的Babel插件配置和
jsxImportSource设置,确保编译时能正确处理组件选择器语法
内容的提问来源于stack exchange,提问作者maja
相关产品推荐
相关产品推荐

