【问题标题】:changing custom colors of a material-UI component to adjust dark mode更改材质 UI 组件的自定义颜色以调整暗模式
【发布时间】:2021-05-17 05:58:23
【问题描述】:

您好,我有一个用于 Material-UI 应用程序的定制芯片组件,我正在使用灰色对象更改芯片的背景和边框颜色

现在当我通过全局主题切换到暗模式时 调色板:{ 类型:“黑暗” } 那些颜色不变。如果我们处于浅色或深色模式,是否有某种方法可以更改这些自定义颜色?

import React, { useState } from 'react';
import grey from'@material-ui/core/colors/grey';
import {Chip} from "@material-ui/core";
import {withStyles} from "@material-ui/core/styles";


const MyChip = withStyles(theme =>({
    root: {
         backgroundColor:grey[100],
         borderStyle: "solid",
         borderWidth: "1px",
         borderColor: grey[300]
    },
}))(Chip);

const ChipComponent = ({...props}) => {
    return <MyChip {...props} />
}

export default ChipComponent;

【问题讨论】:

  • “通过主题切换到深色模式”具体是什么意思?我问的原因是我想知道你是否可以这样做:backgroundColor: theme.darkMode ? grey[800] : grey[100],
  • @BenStephens,感谢您的澄清,在我的应用程序中,我有一个自定义主题,该主题放置在单独的 Theme.js 文件中,并通过 在这个全局主题中,我可以通过调色板在暗模式和亮模式之间切换:{ type: "light", } 它可以设置为 type: "dark",
  • @BenStephens 现在我将您的建议添加到我的自定义芯片组件 backgroundColor: theme.darkMode ? gray[800] : gray[100] 看起来它没有识别darkMode(即使它设置在 Theme,js 文件中,因为它只应用了正确的参数 gray[100]
  • 类似:backgroundColor: theme.palette.type === 'dark' ? grey[800] : grey[100] 怎么样?希望这只是在主题中找到正确的属性来判断您是否处于黑暗模式的问题。

标签: reactjs material-ui


【解决方案1】:

根据@BenStephens 的解决方案(见原问题的cmets) 解决方案是添加 theme.palette.type === 'dark' ? gray[800] : gray[100] 到背景/边框颜色

import React, { useState } from 'react';
import {Chip} from "@material-ui/core";
import { createMuiTheme } from '@material-ui/core/styles';

import {withStyles} from "@material-ui/core/styles";
import { useTheme } from '@material-ui/core/styles';

import grey from'@material-ui/core/colors/grey';

const MyChip = withStyles(theme =>({
root: {
     backgroundColor:theme.palette.type=='dark'? grey["700"]:grey["100"],
     borderStyle: "solid",
     borderWidth: "1px",
     borderColor: theme.palette.grey[300]
},
}))(Chip);


const ChipComponent = ({...props}) => {
    return <MyChip {...props} />
}

export default ChipComponent;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-24
    • 2021-02-09
    • 2019-09-26
    • 2019-04-17
    • 2021-12-26
    • 1970-01-01
    相关资源
    最近更新 更多