You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Vanilla Extract中选择硬编码CSS类?

在Vanilla Extract中选择第三方组件的硬编码类

问题场景

我正从Emotion迁移到Vanilla Extract,组件中包含一个第三方UI库组件,该组件带有硬编码类.ClassWhichICannotChange。在Emotion中我通过以下方式自定义样式:

// Emotion 写法
export const button = css({
    backgroundColor: "#green",
    "& .ClassWhichICannotChange": {
        padding: 6,
    },
});

但在Vanilla Extract中尝试相同写法时,出现TypeScript类型错误:

// Vanilla Extract 错误写法
export const button = style({
    backgroundColor: "green",
    "& .ClassWhichICannotChange": {
        padding: 6,
    },
});
// 错误提示:Object literal may only specify known properties, and '& .ClassWhichICannotChange' 
// does not exist in type 'ComplexStyleRule'.ts(2353)

对应的HTML结构示例:

<MyComponent className={button}>
   <ThirdPartyLibraryComponent /> <!-- 该组件内部包含硬编码CSS类 .ClassWhichICannotChange -->
</MyComponent>

解决方案

Vanilla Extract的style函数对样式结构有明确约束,嵌套选择器不能直接写在根样式对象中,需要通过selectors属性统一管理。正确写法如下:

// Vanilla Extract 正确写法
export const button = style({
    backgroundColor: "green",
    selectors: {
        "& .ClassWhichICannotChange": {
            padding: 6,
        },
    },
});

这种写法符合Vanilla Extract的类型规范,能正确选中第三方组件内部的硬编码类并应用自定义样式。


内容的提问来源于stack exchange,提问作者Black Beard

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.20 21:32:11