如何在道具中传递颜色来改变主题?

How to pass color in props to change theme?

您好,我正在尝试通过 color: primary 或 color: secondary 来更改颜色,但我不知道该怎么做。

// @flow

import * as React from 'react';
import withStyles from '@material-ui/core/styles/withStyles';
import type { Theme } from '@material-ui/core/styles/createMuiTheme';
import classnames from 'classnames';

export const styles = (theme: Theme) => ({
  root: {
    backgroundColor: theme.palette.primary.main,
    width: '80px',
    height: '80px',
  },
  colorPrimary: {
    backgroundColor: theme.palette.primary.main,
  },
  colorSecondary: {
    backgroundColor: theme.palette.secondary.main,
  },
});

export type Props = {
  className?: string,
  classes: { [$Keys<$Call<typeof styles, Theme>>]: string },
  color?: string,
};

const TMPask = ({ classes, className, color }: Props) => (
  <div
    className={classnames(classes.root, className, {
      [classes.colorPrimary]: color === 'primary',
      [classes.colorSecondary]: color === 'secondary',
    })}
  >
    hello
  </div>
);

TMPask.defaultProps = {
  className: undefined,
  color: 'Primary',
};

export default withStyles(styles)(TMPask);

我需要样式 const 中的选择器在这两个主题之间切换,我想我需要一个 if 条件来让 colorPrimary o colorSecondary 应用覆盖根 class,有什么帮助吗?

您可以将其转换为 useStyles 钩子并自己传递道具:

// @flow

import * as React from 'react';
import makeStylesfrom '@material-ui/core/styles/makeStyles';
import type { Theme } from '@material-ui/core/styles/createMuiTheme';
import classnames from 'classnames';

export const useStyles = makeStyles((theme: Theme) => ({
  root: {
    backgroundColor: ({color}) => color === 'primary' ? theme.palette.primary.main : theme.palette.secondary.main,
    width: '80px',
    height: '80px',
  },
  colorPrimary: {
    backgroundColor: ({color}) => color === 'primary' ? theme.palette.primary.main : theme.palette.secondary.main,
  },
  colorSecondary: {
    backgroundColor: ({color}) => color === 'primary' ? theme.palette.primary.main : theme.palette.secondary.main,
  },
}));

export type Props = {
  className?: string,
  color?: string,
};

const TMPask = ({ color }: Props) => {
  const classes = useStyles({color})
  return <div
    className={classes.root}
  >
    hello
  </div>
};

TMPask.defaultProps = {
  className: undefined,
  color: 'Primary',
};

export default TMPask;

我不确定你的 className 是做什么的,但我想它现在也可以删除了。

更快的方法是直接访问道具,因为样式对象也接受每个值的函数。这允许您访问传递给组件的所有道具。而且由于您无论如何都要将 'color' 传递给它:

export const styles = (theme: Theme) => ({
  root: {
    backgroundColor: ({color}) => color === 'primary' ? theme.palette.primary.main : theme.palette.secondary.main,
    width: '80px',
    height: '80px',
  },
  colorPrimary: {
    backgroundColor: ({color}) => color === 'primary' ? theme.palette.primary.main : theme.palette.secondary.main,
  },
  colorSecondary: {
    backgroundColor: ({color}) => color === 'primary' ? theme.palette.primary.main : theme.palette.secondary.main,
  },
});