如何在React中的外部文件上设置Material UI(withStyle)样式? [英] How to set Material UI (withStyle) style on an external file in React?

查看:528
本文介绍了如何在React中的外部文件上设置Material UI(withStyle)样式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to put all my styles in an external file to be cleaner but i can't find the solution to do it.

例如,我有这样的东西:

For exemple, i've got something like this:

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

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

with this at the end of my App component:

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

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

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

But if i'm trying to put my style outside of my component and import it, I can't access to theme.zIndex.drawer

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

My external style file is looking like this:

const drawerWidth = 240;

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

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

I don't understand very well how it works, does someone can help me ?

推荐答案

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

When the style was within the App.jsx, is was a function, when you moved it to a seperate file, you made it an object.

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

You need to export a function, not a JSON object:

const drawerWidth = 240;

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

这篇关于如何在React中的外部文件上设置Material UI(withStyle)样式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆