React: How to combine each multiple styles marked in Material-UI

≡放荡痞女 提交于 2020-03-23 12:05:10

问题


I have two styles.

One thing is included in specific components, another thing is included in global components.

for example, let's suppose that we have the following tree.

index.tsx
-App.tsx
-globalConstants.ts

in globalConstants.ts

import { Theme, makeStyles, createStyles } from '@material-ui/core/styles';

export const sharedStyles = makeStyles((theme: Theme) =>
  createStyles({
    .
    .
    .
  }),
);

in App.tsx

import React from 'react';
import { Theme, makeStyles, createStyles } from '@material-ui/core/styles';
import { sharedStyles } from '../constants/globalConstants'

const useStyles = makeStyles((theme: Theme) =>
  createStyles({
    .
    .
    .
  }),
);

My problem is I can't combine useStyles and sharedStyles into one classes variable.

Of course, I can use this like following

export default function NavBar() {
  const classes = useStyles();
  const sharedClasses = sharedStyles();
}

But I'd like to combine classes and sharedClasses into one constants such as

const classes = {useStyles()+sharedStyles())

Is there some good way how to combine that?


回答1:


Well, it seems to lead us to an open-based answer, still, I'd like to provide some approach that I have found.

Refer to material-ui official document: styles_advanced

You can use third-party libs like clsx.

import clsx from 'clsx';
import { makeStyles } from '@material-ui/core/styles';

const useStylesBase = makeStyles({
  root: {
    color: 'blue', // 🔵
  },
});

const useStyles = makeStyles({
  root: {
    color: 'red', // 🔴
  },
});

export default function MyComponent() {
  // Order doesn't matter
  const classes = useStyles();
  const classesBase = useStylesBase();

  // Order doesn't matter
  const className = clsx(classes.root, classesBase.root)

  // color: red 🔴 wins.
  return <div className={className} />;
}

I'm sure there are many similar libs so choose the one you feel good about.

And you can implement it by yourself, refer to the sample in this issue

function combineStyles(...styles) {
  return function CombineStyles(theme) {
    const outStyles = styles.map((arg) => {
      // Apply the "theme" object for style functions.
      if (typeof arg === 'function') {
        return arg(theme);
      }
      // Objects need no change.
      return arg;
    });

    return outStyles.reduce((acc, val) => Object.assign(acc, val));
  };
}

export default combineStyles;

Hope this answer would find you well.



来源:https://stackoverflow.com/questions/60714277/react-how-to-combine-each-multiple-styles-marked-in-material-ui

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