简体   繁体   English

Material-UI,如何在打字稿中将多种样式与主题合并?

[英]Material-UI, how to merge multiple styles with theme in typescript?

I have two styles.我有两种风格。

in global.ts在 global.ts

const globalStyles = (theme: Theme) => {
  return {
    g: {
      marginRight: theme.spacing(40),
    },
  }
}

export const mergedStyle = (params: any) => makeStyles((theme: Theme) =>
  createStyles({
    ...globalStyles,
    ...params
  }),
);

in App.tsx在 App.tsx

import * as Global from './global';

const localStyles = (theme: Theme) => {
  return {
    l: {
      marginRight: theme.spacing(20),
    },
  }
}

export default function DenseAppBar() {
  const classes = Global.mergedStyle(localStyles)();

  return (
    <div>
      <MenuIcon className={classes.l} />
      <MenuIcon className={classes.g} />
      <MenuIcon />
    </div>
  );
}

It doesn't have any compile error, but it doesn't work.它没有任何编译错误,但它不起作用。 How should I modify my code?我应该如何修改我的代码?

I added codesandbox.我添加了代码和框。

https://codesandbox.io/s/confident-hamilton-6eect https://codesandbox.io/s/confident-hamilton-6eect

Use a common makeStyles to generate the inner content with spread_syntax would be fine.使用通用的makeStyles生成带有spread_syntax的内部内容就可以了。

const style1 = (theme) => {
  return {
    a: {
      marginRight: theme.spacing(1),
    }
  }
}
const style2 = (theme) => {
  return {
    b: {
      marginRight: theme.spacing(2),
    }
  }
}
const mergedStyle = makeStyles((theme: Theme) =>
  createStyles({
    ...style1(theme),
    ...style2(theme),
  }),
);

Usage用法

export default function MyComponent() {
  const classes = mergedStyle();
  return (
    <>
      <div className={classes.a}></div>
      <div className={classes.b}></div>
    </>
  )
}

Try it online:在线试一下:

编辑friendly-goldstine-t5dhj


Update更新

If you want to pass params in mergeStyle function如果要在mergeStyle函数中传递参数

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

usage用法

const classes = mergedStyle(params)();

Related question: how-to-combine-each-maked-styles-in-material-ui相关问题: how-to-combine-each-made-styles-in-material-ui

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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