如何在 React 中的外部文件上设置 Material UI (withStyle) 样式?

2024-01-11

我试图将所有样式放入外部文件中以使其更清晰,但我找不到解决方案。

例如,我有这样的东西:

  const styles = theme => ({
    appBar: {
      zIndex: theme.zIndex.drawer + 1,
      position: 'absolute',
      marginLeft: drawerWidth,
      width: '100%',
    },
  });

在我的应用程序组件的末尾:

App.propTypes = {
  classes: PropTypes.object.isRequired,
  theme: PropTypes.object.isRequired,
};

export default withStyles(styles, { withTheme: true })(App);

但是如果我尝试将样式放在组件之外并导入它,我将无法访问 theme.zIndex.drawer

我的外部样式文件如下所示:

const drawerWidth = 240;

export default {
  appBar: {
    zIndex: theme.zIndex.drawer + 1,
    position: 'absolute',
    marginLeft: drawerWidth,
    width: '100%',
  },
}

我不太明白它是如何工作的,有人可以帮助我吗?


当样式位于 App.jsx 中时,它是一个函数,当您将其移动到单独的文件时,您将其设为一个对象。

您需要导出一个函数,而不是 JSON 对象:

const drawerWidth = 240;

export default theme => ({
  appBar: {
    zIndex: theme.zIndex.drawer + 1,
    position: 'absolute',
    marginLeft: drawerWidth,
    width: '100%',
  },
})
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在 React 中的外部文件上设置 Material UI (withStyle) 样式? 的相关文章

随机推荐