【问题标题】:When I click the button, I want to change the page background color to another color, not black, how can I do it?当我点击按钮时,我想将页面背景颜色更改为另一种颜色,而不是黑色,我该怎么做?
【发布时间】:2022-01-24 05:45:51
【问题描述】:
const DarkTheme = () => {
  const [dark, setDark] = useState(false)

  const theme = createMuiTheme({
      palette: {
          type: dark ? 'dark' : 'light',`I want to make another color instead of dark`
      },
  })

当我点击按钮时,我想将页面背景颜色更改为另一种颜色,而不是黑色,我该怎么办?

  return (
      <ThemeProvider theme={theme}>
           //toggle
          <Switch checked={dark} onChange={() => setDark(!dark)} />
          <Paper>
              <Typography variant='h1'>This is a h1 text</Typography>

              <Typography variant='body2'>This is a body2 text</Typography>
          </Paper>
      </ThemeProvider>
  )
}

https://stackoverflow.com

【问题讨论】:

标签: reactjs next.js


【解决方案1】:

您可以使用自定义palette 设计来创建自己的暗模式。

像这里一样,我为 暗模式 创建了 pink color 背景,在 l夜间模式 中创建了 blue text

import {useState} from 'react';
import { createTheme, ThemeProvider } from '@mui/material/styles';
import { amber, pink,blue } from '@mui/material/colors';

import Paper from '@mui/material/Paper'
import Typography from '@mui/material/Typography'
import Switch from '@mui/material/Switch';



export default function Palette() {

  const [dark, setDark] = useState(false);
  const theme = createTheme({
    palette: {
      dark,
    primary: {
      ...amber,
      ...(dark === true && {
        main: amber[300],
      }),
    },
    ...(dark === true && {
      background: {
        default: pink[900],
        paper: pink[900],
      },
    }),
    text: {
      ...(dark === false
        ? {
            primary: blue[900],
            secondary: blue[800],
          }
        : {
            primary: '#fff',
            secondary: blue[500],
          }),
    },
    },
    });

  return (
    <ThemeProvider theme={theme}>
      
      <Switch checked={dark} onChange={() => setDark(!dark)} />
        <Paper>
          <Typography variant='h1'>This is a h1 text</Typography>

              <Typography variant='body2'>This is a body2 text</Typography>
          </Paper>
    </ThemeProvider>
  );
}

【讨论】:

  • 非常感谢我的朋友,它帮了很多忙
  • 输入'{ text: { primary: "#0d47a1";次要:“#1565c0”; } | {主要:字符串;次要:“#2196f3”; };背景?:{默认值:“#880e4f”;纸:“#880e4f”; } |不明确的;黑暗:布尔值;主要:{主要?:“#ffd54f”|不明确的; ... 13 更多 ...; A700: "#ffab00"; }; }' 不可分配给类型 'PaletteOptions'。对象字面量只能指定已知属性,'PaletteOptions'.ts(2322) 类型中不存在'dark'
  • 我收到这样的错误
  • 不要将其分配给type。你可以简单地复制粘贴我的代码吗?如果问题再次出现,我会分享codeandbox链接
  • 我分享了我的问题
猜你喜欢
  • 2021-03-14
  • 2019-09-22
  • 1970-01-01
  • 2015-02-10
  • 1970-01-01
  • 2020-04-03
  • 1970-01-01
  • 1970-01-01
  • 2014-02-10
相关资源
最近更新 更多