【问题标题】:Material-UI Typescript How to make create style instance from makeStyle() in a component classMaterial-UI Typescript 如何在组件类中从 makeStyle() 创建样式实例
【发布时间】:2020-03-20 21:40:29
【问题描述】:

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

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

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

由于我使用的是 Typescript,我的 prop 接口是否需要一些东西或者我需要做一些事情,例如

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

为 withStyle() 工作? 参考:Is there a non-hook alternative for the React Material-UI makeStyles() function that works for class Components

【问题讨论】:

  • 非钩子替代方案是withStyles,它适用于函数式组件和基于类的组件。您的代码应该按原样工作。您的问题可能出在其他地方。您能否发布问题的沙盒和/或 sn-p?
  • 哦!这是我自己的答案哈哈哈哈

标签: reactjs typescript material-ui


【解决方案1】:

Ryan Cogswell 答案是最佳答案。引用:

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

效果非常好。谢谢你:)

【讨论】:

    猜你喜欢
    • 2021-11-18
    • 2020-07-30
    • 2020-07-05
    • 2019-02-14
    • 1970-01-01
    • 2020-03-20
    • 1970-01-01
    • 2019-10-26
    • 1970-01-01
    相关资源
    最近更新 更多