next.js 在MUI5中向makeStyle传递props(TypeScript)

jxct1oxe  于 2023-05-28  发布在  TypeScript
关注(0)|答案(1)|浏览(253)

我有下面的MUI4代码迁移到MUI5。
在MUI4下,我有:

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

type Props = {
  darkMode?: boolean;
};

const useStyles = makeStyles<Theme, Props>((theme: Theme) =>
  createStyles({
    button: (props: Props) => ({
      color: props.darkMode ? '#fff' : '#AE4',
    }),
  }),
);

export default useStyles;

重写MUI5:

import { makeStyles } from 'tss-react/mui'
import { Theme } from '@mui/material/styles'

type Props = {
  darkMode?: boolean;
};

const useStyles = makeStyles<Theme, Props>((theme: Theme) => ({
  return {
    button: (props: Props) => ({
      color: props.darkMode ? '#fff' : '#AE4',
    }),
  }
})

我遇到了错误

Type 'Props' does not satisfy the constraint 'string'.ts(2344)

正确的做法是什么?

unguejic

unguejic1#

docs中很好地定义了如何实现这一点:

const getDesignTokens = (mode: PaletteMode) => ({
  palette: {
    mode,
    ...(mode === 'light'
      ? {
          // palette values for light mode
          primary: amber,
          divider: amber[200],
          text: {
            primary: grey[900],
            secondary: grey[800],
          },
        }
      : {
          // palette values for dark mode
          primary: deepOrange,
          divider: deepOrange[700],
          background: {
            default: deepOrange[900],
            paper: deepOrange[900],
          },
          text: {
            primary: '#fff',
            secondary: grey[500],
          },
        }),
  },
});
const [mode, setMode] = React.useState<PaletteMode>('light');
const colorMode = React.useMemo(
  () => ({
    // The dark mode switch would invoke this method
    toggleColorMode: () => {
      setMode((prevMode: PaletteMode) =>
        prevMode === 'light' ? 'dark' : 'light',
      );
    },
  }),
  [],
);

// Update the theme only if the mode changes
const theme = React.useMemo(() => createTheme(getDesignTokens(mode)), [mode]);

相关问题