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

react-jss的createUseStyles结合theme与props的TypeScript类型问题

react-jss createUseStyles 同时支持Theme和组件Props的TypeScript正确写法

类型报错根源

  1. 自定义Theme未关联react-jss全局类型定义,导致TS无法识别theme字段
  2. 无需手动将useTheme获取到的theme传入useStyles,createUseStyles生成的Hook会自动从ThemeProvider上下文读取theme,手动传入反而会触发类型不匹配问题

解决方案

方式1:全局扩展Theme类型(推荐,项目共用一套Theme时使用)

首先扩展react-jss的DefaultTheme全局接口,让TS自动识别你自定义的theme结构:

// 可以写在全局类型声明文件如 typings.d.ts 中,也可以写在当前组件文件顶部
declare module 'react-jss' {
  interface DefaultTheme {
    colorPrimary: string;
    altColor: string;
  }
}

之后给createUseStyles传入第一个泛型参数,指定接收的组件Props类型,样式回调会自动注入props和theme两个参数,且类型自动推导:

import React, { ReactNode } from "react";
import { createUseStyles, ThemeProvider } from "react-jss";

// 组件Props定义
interface Props {
  children: ReactNode;
  useRed: boolean;
}

// 泛型传入Props类型,样式回调自动支持props+theme的类型提示
const useStyles = createUseStyles<Props>({
  button: {
    background: ({ useRed, theme }) => useRed ? theme.altColor : theme.colorPrimary
  },
  label: {
    fontWeight: "bold"
  }
});

const Button2: React.FC<Props> = ({ children, useRed }) => {
  // 调用useStyles只需要传组件props即可,theme自动从上下文注入
  const classes = useStyles({ useRed });
  return (
    <button className={classes.button}>
      <span className={classes.label}>{children}</span>
    </button>
  );
};

const theme = {
  colorPrimary: "green",
  altColor: "red"
};

const App = () => (
  <ThemeProvider theme={theme}>
    <Button2 useRed={true}>I am a button 2 with red background</Button2>
  </ThemeProvider>
);

export default App;

方式2:单独指定Theme类型(无需全局扩展时使用)

如果不需要全局扩展Theme类型,可以直接给createUseStyles传入第二个泛型参数指定自定义Theme类型:

import { createUseStyles } from "react-jss";

interface PUTheme {
  colorPrimary: string;
  altColor: string;
}

interface Props {
  useRed: boolean;
}

// 第一个泛型是组件Props类型,第二个是自定义Theme类型
const useStyles = createUseStyles<Props, PUTheme>({
  button: {
    background: ({ theme }) => theme.colorPrimary
  }
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 03:18:04