How to set Material UI (withStyle) style on an external file in React?

∥☆過路亽.° 提交于 2019-12-25 02:16:06

问题


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

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);

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 ?


回答1:


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.

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


来源:https://stackoverflow.com/questions/51729702/how-to-set-material-ui-withstyle-style-on-an-external-file-in-react

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!