首页 > 解决方案 > Material-UI Typescript 如何在组件类中从 makeStyle() 创建样式实例

问题描述

Material-UI 中的 makeStyle() 工作正常,但是我将函数组件移动到类组件,现在它导致错误,因为它违反了 React 的钩子规则(调用 React.useContext())

如何在使用类组件时获得与 makeStyle() 相同的结果?似乎 Material-UI 的文档假定所有组件都应该是功能组件,因为我几乎找不到任何类组件示例或信息。

我试过 withStyles(style)(App) 没有运气,因为它会导致一个错误,指出许多属性不兼容,我觉得这很奇怪。

由于我使用的是 Typescript,我的道具界面是否需要某些东西,或者我是否需要做一些事情,例如

const Component = withStyles(styles)(({classes}) =>{
    return <div className={classes.foo} /<
})

为 withStyle() 工作?参考:是否有适用于类组件的 React Material-UI makeStyles() 函数的非挂钩替代方案

标签: reactjstypescriptmaterial-ui

解决方案


Ryan Cogswell的回答是最好的答案。去引用:

See the documentation here: material-ui.com/guides/typescript/#usage-of-withstyles

工作非常出色。谢谢 :)


推荐阅读