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

IT技术 reactjs material-ui
2021-05-04 14:25:00

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

例如,我有这样的事情:

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

在我的 App 组件末尾加上这个:

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%',
  },
}

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

1个回答

当样式在 App.jsx 中时,它是一个函数,当你将它移动到一个单独的文件时,你就将它变成了一个对象。

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

const drawerWidth = 240;

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