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

Preact中能否用styled-components的css函数动态创建CSS类?

在Preact中实现类似SolidJS styled-components的css函数用法

当然可以实现,完全不需要为这个小div创建新组件,以下是几种贴合你使用习惯的方案:

方案1:使用@emotion/css库

这是最接近你SolidJS用法的方案,@emotion/css提供的css函数会动态生成CSS类名并注入样式,支持完整的CSS特性(包括伪类、媒体查询、动态值)。

步骤:

  1. 安装依赖:
npm install @emotion/css
  1. 在组件中直接使用:
import { css } from '@emotion/css';

function YourComponent() {
  // 支持动态值
  const offset = 0;

  return (
    <div className={css`
      top: ${offset}px;
      left: ${offset}px;
      position: absolute; // 补充定位属性让top/left生效
      padding: 10px;
    `}>
      blah blah
    </div>
  );
}

方案2:内联样式(适合极简场景)

如果你的样式非常简单,不需要伪类、媒体查询等特性,可以直接用Preact的内联样式,虽然写法和CSS字符串不同,但不需要额外依赖:

function YourComponent() {
  return (
    <div style={{ top: 0, left: 0, position: 'absolute' }}>
      blah blah
    </div>
  );
}

注意

  • 内联样式不支持CSS伪类(如:hover)、媒体查询等高级特性,所以复杂样式优先选@emotion/css。
  • @emotion/css还支持缓存样式、主题配置等进阶功能,和你在SolidJS中使用的solid-styled-components逻辑一致。

内容的提问来源于stack exchange,提问作者Behnam Ghiaseddin

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 01:15:58