【问题标题】:Material UI Palette not updating材质 UI 调色板未更新
【发布时间】:2020-04-10 07:23:38
【问题描述】:

我是 React 和 Material UI 的新手,我正在尝试使用 createMuiTheme 向 MUI 按钮添加一些自定义样式。

我已经按照文档并几乎复制了该示例,但它没有任何效果,并且控制台中没有抛出任何错误。

我一直在努力解决这个问题,但我看不出问题出在哪里,我错过了什么?

import React from 'react';
import { createMuiTheme } from '@material-ui/core/styles';
import { ThemeProvider } from '@material-ui/styles';
import Button from '@material-ui/core/Button';

const mytheme = createMuiTheme({
    palette: {
        primary: { main: '#1565C0'},
        secondary: { main: '#11cb5f' }, 
    },
});

export const PrimaryButton = (props) => {
    return (
        <ThemeProvider theme={mytheme}>
            <a href={props.buttonLink}>
                <Button
                    style={{ ...props.styles}}
                    onClick={props.handleClick}
                    variant='contained' color='primary' size='large'
                >
                    {props.buttonText}
                </Button>
            </a>
        </ThemeProvider>
    );
};

export const SecondaryButton = (props) => {
    return (
        <ThemeProvider theme={mytheme}>
            <Button
                style={{...props.styles }}
                value={props.value || ''}
                onClick={props.handleClick}
                variant='outlined' color='secondary' size='large'
            >
                {props.buttonText}
            </Button>
        </ThemeProvider>
    )
}

【问题讨论】:

  • 效果很好,我试过codesandbox.io/s/flamboyant-wu-b8kqg。我改变了原色,它可以工作
  • 嘿,谢谢你的设置。我可以看到它在那里工作。问题是默认样式仍在应用中,并且在我的自定义样式之后应用,因此过度编写它们,我不确定为什么会发生这种情况..
  • 您在控制台中是否有任何关于@material-ui/styles 多个实例的警告?
  • 没有控制台警告,下面的答案已经解决了,我需要将整个应用程序包装在 ThemeProvider 中,并全局设置样式而不是每个组件。

标签: reactjs material-ui


【解决方案1】:

它正在工作。尝试改变这一点:

variant='outlined'

通过

variant='contained'

【讨论】:

  • 该道具出现在 PrimaryButton 上。我刚刚检查并提供了样式,但是它们被覆盖了,但是 MUI 样式。
  • 所以我并没有遵循您实际需要的内容。您想更改整个应用程序中的值吗?还是只是在组件中?
  • 所以当我检查开发工具时,我可以看到我的样式被应用到 > MuiButton-containedPrimary。然而,在层次结构的更高层,默认的 MUI 设置被应用并超越了我的风格。我想我需要将它们应用于整个应用程序来解决这个问题?
  • 是的。查看此代码框,如果它对您有帮助,请告诉我。 codesandbox.io/s/agitated-galois-lcryu
  • 不客气。不要忘记选择你的答案......否则人们会尝试回答你。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-01-18
  • 2019-06-03
  • 2019-09-26
  • 2019-07-25
  • 1970-01-01
  • 2020-02-05
  • 2021-12-26
相关资源
最近更新 更多