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

如何在TS工具函数文件中使用Material-UI主题的本地化资源

解决方案

你遇到的报错是React Hook的强制规则限制:所有Hook只能在React函数组件或者自定义Hook内部调用,不允许在文件顶层、普通JS/TS函数中直接调用。以下是两种可行的实现方案:

方案1:将工具函数封装为自定义Hook

这是最符合React规范的实现方式,适合所有工具函数仅给React组件调用的场景。

// 工具函数文件 示例:src/utils/localizedUtils.ts
import { useTheme } from '@mui/material/styles';

// 自定义Hook命名必须以use开头,符合React Hook命名规则
export const useLocalizedUtils = () => {
  const t = useTheme().props;

  // 封装你需要的通用逻辑
  const getGeneralText = (key: string) => {
    return t.General[key] ?? '';
  };

  const formatLocalizedDate = (date: Date) => {
    // 用到t的其他通用逻辑
  };

  return {
    getGeneralText,
    formatLocalizedDate
  };
};

组件内调用方式:

import { useLocalizedUtils } from '@/utils/localizedUtils';

const DemoComponent = () => {
  const { getGeneralText } = useLocalizedUtils();
  return <span>{getGeneralText('someString')}</span>;
};

方案2:将本地化对象作为参数传入工具函数

适合工具函数需要兼容非React场景调用的情况,不需要改造工具为Hook形式,调用时传入本地化对象即可。

// 工具函数文件 示例:src/utils/common.ts
export const getGeneralText = (t: any, key: string) => {
  return t.General[key] ?? '';
};

export const formatLocalizedDate = (t: any, date: Date) => {
  // 其他通用逻辑
};

组件内调用方式:

import { useTheme } from '@mui/material/styles';
import { getGeneralText } from '@/utils/common';

const DemoComponent = () => {
  const t = useTheme().props;
  return <span>{getGeneralText(t, 'someString')}</span>;
};

补充说明

如果需要在完全脱离React组件的场景中调用本地化资源,可以搭配全局状态管理工具(如Zustand、Redux),在应用根组件监听主题变化,将当前的本地化对象同步存入全局状态,非组件场景直接从全局状态读取即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 17:48:02