简体   繁体   中英

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

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM