繁体   English   中英

如何更改 MUI 输入下划线颜色?

[英]How to change MUI input underline color?

我有一个位于深色背景上的 MUI Select组件,因此对于这个组件,我想对其进行更改,以便文本和线条颜色全部为白色。 Select实例的其余部分应保持不变。

虽然我可以让文本和图标改变颜色,但我似乎无法弄清楚如何使用classes道具来设置下划线颜色。 我的尝试似乎也使打开的图标也换行到下一行。 这是一个演示问题的示例:

编辑材料演示

我已经这样设置我的风格:

const styles = theme => ({
  underline: {
    borderBottom: '2px solid white',
    '&:after': {
      // The MUI source seems to use this but it doesn't work
      borderBottom: '2px solid white',
    },
  }
};

然后我是这样设置的:

<Select
  classes={{
    underline: classes.underline,     // Does it go here?
  }}
  inputProps={{
    classes: {
      underline: classes.underline,   // Or does it go here?
    },
  }}
>

此方法确实适用于文本(上面未显示,但在链接示例中),它只是我无法更改的下划线颜色。 我错过了什么?

您可以使用两个选项更改Select Component 的下划线颜色

1. 用类覆盖

使用input道具创建一个<Input />元素并使用underline键覆盖使用类。

<Select
            value={this.state.age}
            onChange={this.handleChange}
            input={<Input classes={{
              underline: classes.underline,
            }}
             name="age" id="age-helper" />}>

我在你的沙箱中应用了这个,在这里看看这个

2. 使用MuiThemeProvider

const theme = createMuiTheme({
  palette: {
    primary: green,
  },
});

并使用<MuiThemeProvider/>应用主题

我在这个沙箱中都应用了

自定义选择

如果目标只是转动下划线(以及文本),有一个非常简单的解决方案,它也适用于许多其他组件( <Input><TextField>等):

const theme = createMuiTheme({
    palette: {
      type: 'dark',
    },
  });

它将捕捉下划线并将其变成白色。

有关这将更改的详细信息,如果您想覆盖它的元素: https : //material-ui.com/customization/palette/#dark-mode

(如果您以前从未使用过主题,则需要导入createMuiTheme并将您的组件包装在其中;请参阅https://material-ui.com/customization/theming/

MUI v5 中,您可以使用sx道具。 以下是具有自定义下划线颜色的 3 个不同组件的示例:

<Input
  sx={{
    ':before': { borderBottomColor: 'red' },
    // underline when selected
    ':after': { borderBottomColor: 'red' },
  }}
/>
<TextField
  variant="standard"
  sx={{
    '& .MuiInput-underline:before': { borderBottomColor: 'orange' },
    '& .MuiInput-underline:after': { borderBottomColor: 'orange' },
  }}
/>
<Select
  variant="standard"
  sx={{
    ':before': { borderBottomColor: 'purple' },
    ':after': { borderBottomColor: 'purple' },
  }}
>

另一种选择是styled()

const options = {
  shouldForwardProps: (prop) => prop !== 'underlineColor',
};
const StyledSelect = styled(
  Select,
  options,
)(({ underlineColor }) => ({
  ':before, :after': {
    borderBottomColor: underlineColor,
  },
}));
<StyledSelect variant="standard" underlineColor="green">

现场演示

代码沙盒演示

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM