如何更改Material-ui单选按钮选中的颜色?

时间:2018-06-11 14:33:42

标签: javascript reactjs radio-button material-ui

color道具只能取三个值(默认,主要,辅助),但如果我希望我的收音机为绿色怎么办?

所以我尝试覆盖classes道具,如此:

const styles = theme => ({
  radio: {
    colorPrimary: {
    '&$checked': {
      color: 'blue'
    }
  },
  checked: {},
  } 
})

然后在组件内部:

<FormControlLabel
   classes={{root: classes.formControlLabelRoot, label: classes.formControlLabel}}
   value="week"
   control={<Radio disableRipple classes={{colorPrimary: classes.radio}} />}
   label="Every week (Monday at 12:00)"
/>

但这不起作用。

3 个答案:

答案 0 :(得分:6)

找到解决方案:

const styles = theme => ({
  radio: {
    '&$checked': {
      color: '#4B8DF8'
    }
  },
  checked: {}
})

在组件内部:

<FormControlLabel
  classes={{root: classes.formControlLabelRoot, label: classes.formControlLabel}}
  value="day"
  control={
    <Radio
      disableRipple
      classes={{root: classes.radio, checked: classes.checked}}
    />
  }
  label="Every Day (at 12:00)"
/>

您必须拥有root密钥。

答案 1 :(得分:4)

对于项目范围的主题,我有不同的解决方案。

const theme = {
  overrides: {
    MuiRadio: {
      root: {
        color: 'green',
      },
      colorSecondary: {
        '&$checked': {
          color: 'green',
        },
      },
    },
  },
},

const muiTheme = createMuiTheme(theme)

<ThemeProvider theme={muiTheme}>
  // rest of app goes here
</ThemeProvider>

这样,应用中所有 Material-UI Radio 元素的外圈都是绿色的,选中时也是内圈的绿色。

答案 2 :(得分:0)

我认为您需要使用 colorSecondary 类键而不是colorPrimary,因为单选按钮的颜色为 secondary 为默认值

您还可以使用根组件中的 createMuiTheme MuiThemeProvider 组件覆盖主要和辅助颜色以及默认颜色的默认值

import React from 'react';
import { MuiThemeProvider, createMuiTheme } from '@material-ui/core/styles';
import purple from '@material-ui/core/colors/purple';
import Button from '@material-ui/core/Button';

const theme = createMuiTheme({
  palette: {
    primary: { main: purple[500] }, // Purple and green play nicely together.
    secondary: { main: '#11cb5f' }, // This is just green.A700 as hex.
  },
});

function App() {
  return (
    <MuiThemeProvider theme={theme}>
      <div>
        <Button color="primary">Primary</Button>
        <Button color="secondary">Secondary</Button>
      </div>
    </MuiThemeProvider>
  );
}

export default App;

正如您在下面的示例中所看到的,您只需使用 MuiThemeProvider 包装组件,现在每个组件都将具有新的主要和次要颜色

从material-ui网站查看此链接以获取更多信息 Themes