【问题标题】:Export helper functions with Material-UI theme support导出具有 Material-UI 主题支持的辅助函数
【发布时间】:2021-11-29 13:24:40
【问题描述】:

我想创建一个新文件,其中包含多个使用相同逻辑的组件的辅助函数, 问题是我需要在该文件中使用我的locale.ts 文件来根据主题使用当前语言(本地化) 但似乎我无法在 ts 文件中调用 const t: any = useTheme().props。 (错误:React Hook "useTheme" 不能在顶层调用。必须在 React 函数组件或自定义 React Hook 函数中调用 React Hooks)

今天在我的 tsx 组件文件中:

t: any = useTheme().props
t.General.someString

如何在我的辅助函数文件中使用 Material-UI 主题的本地化?

【问题讨论】:

    标签: reactjs material-ui localization material-design tsx


    【解决方案1】:

    Hook 不能在顶层使用,这是不支持的:

    // top level
    const any = useTheme().props;
    

    它应该在功能组件或其他钩子中使用。参考hookhere的规则:

    function Component() {
      // valid because it's inside a React function
      const any = useTheme().props;
      return (...);
    }
    

    你可以做的是创建一个帮助钩子来返回你需要的特定数据:

    const useThemeProps = () => {
      // valid because it's inside another hook
      return useTheme().props;
    }
    
    function Component() {
      const any = useThemeProps();
      return (...);
    }
    

    你也可以直接返回数据:

    function Component() {
      const { props } = useTheme();
      return (...);
    }
    

    【讨论】:

    • 辅助钩子将如何帮助我?它仍然是一个钩子,我不能在顶级文件中使用它
    • @Ar26 如果您需要在功能组件之外访问主题对象,请使用createTheme() 创建一个默认主题并将其传递给ThemeProvider
    • 实际上,我使用了你的想法——在顶层文件中创建了一个辅助钩子,并在钩子中调用 useTheme().props,用它来构建我的本地化对象并在我的功能组件,谢谢!
    猜你喜欢
    • 2016-03-14
    • 2020-03-09
    • 2021-01-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-29
    • 2020-08-14
    • 1970-01-01
    相关资源
    最近更新 更多