簡體   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