簡體   English   中英

如何更改 MUI TextField 的邊框顏色

[英]How to change the border color of MUI TextField

我似乎無法弄清楚如何更改輪廓變體TextField的輪廓顏色

我查看了 GitHub 個問題,人們似乎指向使用TextField “InputProps”屬性,但這似乎無濟於事。

這是領域

這是我當前的代碼 state

import React from 'react';
import { withStyles } from '@material-ui/core/styles';
import TextField from '@material-ui/core/TextField';
import PropTypes from 'prop-types';

const styles = theme => ({
  field: {
    marginLeft: theme.spacing.unit,
    marginRight: theme.spacing.unit,
    height: '30px !important'
  },
});

class _Field extends React.Component {
      render() {
          const { classes, fieldProps } = this.props;
             return (
                <TextField
                {...fieldProps}
                label={this.props.label || "<Un-labeled>"}
                InputLabelProps={{ shrink: true }} // stop from animating.
                inputProps={{ className: classes.fieldInput }}
                className={classes.field}
                margin="dense"
               variant="outlined"
            />
        );
    }
}

_Field.propTypes = {
    label: PropTypes.string,
    fieldProps: PropTypes.object,
    classes: PropTypes.object.isRequired
}

export default withStyles(styles)(_Field);

https://codesandbox.io/s/6rx8p

                      <CssTextField      

                       label="Username"

                       className="username"
                       name="username"
                       onChange={this.onChange}
                       type="text"
                       autoComplete="current-password"
                       margin="normal"
                       inputProps={{ style: { fontFamily: 'nunito', color: 'white'}}}

                    />

//聲明const並添加材質UI樣式

const CssTextField = withStyles({
  root: {
    '& label.Mui-focused': {
      color: 'white',
    },
    '& .MuiInput-underline:after': {
      borderBottomColor: 'yellow',
    },
    '& .MuiOutlinedInput-root': {
      '& fieldset': {
        borderColor: 'white',
      },
      '&:hover fieldset': {
        borderColor: 'white',
      },
      '&.Mui-focused fieldset': {
        borderColor: 'yellow',
      },
    },
  },
})(TextField);

看看這個,我做了一個快速演示:

https://stackblitz.com/edit/material-ui-custom-outline-color

它更改 Material-UI TextField 的默認邊框顏色和標簽顏色,但在獲得焦點時保持原色。

另外,看看這個鏈接,它給了我“想法”:

https://github.com/mui-org/material-ui/issues/13347

如果您想在聚焦時更改顏色,請查看文檔中的這些示例:

https://mui.com/components/text-fields/#customization

const styles = theme => ({
  notchedOutline: {
    borderWidth: "1px",
    borderColor: "yellow !important"
  }
});

 <TextField
              variant="outlined"
              rows="10"
              fullWidth
              InputProps={{
                classes: {
                  notchedOutline: classes.notchedOutline
                }
              }}
              id="standard-textarea"
              label="Input Set"
              helperText="Enter an array with elemets seperated by , or enter a JSON object"
              placeholder="Placeholder"
              multiline
              value={"" + this.props.input}
              onChange={this.props.handleChangeValue("input")}
              className={classes.textField}
              margin="normal"
            />

在此處輸入圖像描述

如果有人想用樣式組件來做到這一點:

import styled from "styled-components";
import {TextField} from "@material-ui/core";

const WhiteBorderTextField = styled(TextField)`
  & label.Mui-focused {
    color: white;
  }
  & .MuiOutlinedInput-root {
    &.Mui-focused fieldset {
      border-color: white;
    }
  }
`;

這花了我太長時間才弄清楚。 希望它可以幫助某人。

Textfield 邊框的問題是您要設置的顏色的特異性低於 Material-UI (MUI) 設置的原始樣式。

例如 MUI 在聚焦時設置這個類:

.MuiOutlinedInput-root.Mui-focused .MuiOutlinedInput-notchedOutline {
    border-color: (some color);
}

這比自定義選擇器更具體,例如:

.Component-cssNotchedOutline {
    border-color: #f0f;
}

解決方案 A (不推薦)

您可以將!important例外添加到顏色,但這是“不好的做法”

import React from 'react';
import { createStyles, TextField, WithStyles, withStyles } from '@material-ui/core';
interface IProps extends WithStyles<typeof styles> {}

const styles = createStyles({
    notchedOutline: { borderColor: '#f0f !important' },
});

export const TryMuiA = withStyles(styles)((props: IProps) => {
    const { classes } = props;
    return ( <TextField variant={ 'outlined' } label={ 'my label' }
        InputProps={ {
            classes: {
                notchedOutline: classes.notchedOutline,
            },
        } }
    /> );
});

解決方案 B (推薦)

官方 MUI 示例使用其他方式來增加特異性。

“訣竅”不是直接設置元素的樣式,例如:

.someChildElement { border-color: #f0f }

但是要添加一些額外的選擇器(比 MUI 更多*),例如:

.myRootElement.someExtra { border-color: #f0f }
.myRootElement .someChildElement { border-color: #f0f }
...

*(實際上,使用與 MUI 相同的選擇器可能就足夠了,因為如果選擇器的特異性相同,則使用“后”的選擇器。但在SSR的情況下,CSS 規則的順序可能會在補液。)

包括父元素:您可能已經注意到設置notchedOutline確實為未聚焦的元素設置了顏色,但沒有為聚焦的元素設置顏色。 這是因為 MUI 樣式包含輸入框的元素( .MuiOutlinedInput-root.Mui-focused )。 所以你也需要包括父母。

import React from 'react';
import { withStyles } from '@material-ui/core/styles';
import TextField from '@material-ui/core/TextField';

const styles = {
    root: {                           // - The TextField-root
        border: 'solid 3px #0ff',     // - For demonstration: set the TextField-root border
        padding: '3px',               // - Make the border more distinguishable

        // (Note: space or no space after `&` matters. See SASS "parent selector".)
        '& .MuiOutlinedInput-root': {  // - The Input-root, inside the TextField-root
            '& fieldset': {            // - The <fieldset> inside the Input-root
                borderColor: 'pink',   // - Set the Input border
            },
            '&:hover fieldset': {
                borderColor: 'yellow', // - Set the Input border when parent has :hover
            },
            '&.Mui-focused fieldset': { // - Set the Input border when parent is focused 
                borderColor: 'green',
            },
        },
    },
};

export const TryMui = withStyles(styles)(function(props) {
    const { classes } = props;
    return (<TextField label="my label" variant="outlined"
        classes={ classes }
    />);
})

請注意,您可以以不同的方式增加特異性,例如這也可以(有點不同):

    '& fieldset.MuiOutlinedInput-notchedOutline': {
        borderColor: 'green',
    },

備注:當你並不真正“需要”它們時,添加選擇器只是為了增加特異性可能看起來有點“臟”。 我認為是,但這種解決方法有時是自 CSS 發明以來唯一的解決方案,因此它被認為是可以接受的

  inputProps={{ style: { fontFamily: 'nunito', color: 'white'}}}

Inputprops 通過在文本字段中輸入輸入數據的樣式來工作,我們也可以使用 className 進行自定義着色。

      const CssTextField = withStyles({
     root: {
    '& label.Mui-focused': {
     color: 'white',
      },
     '& .MuiInput-underline:after': {
      borderBottomColor: 'yellow',
     },
    '& .MuiOutlinedInput-root': {
     '& fieldset': {
     borderColor: 'white',
     },
     '&:hover fieldset': {
      borderColor: 'white',
       },
     '&.Mui-focused fieldset': {
       borderColor: 'yellow',
     },
     },
    },

這種 const 樣式適用於文本文件的外部部分......

上面要求更改材質 UI 外部的樣式...

使用它覆蓋 CSS 屬性

.MuiFormLabel-root.Mui-focused {
  color: red !important;
}
.MuiOutlinedInput-root.Mui-focused .MuiOutlinedInput-notchedOutline {
  border-color: red !important;
}

對於最新的 MUI v5.2.2: 更改 TextField 顏色屬性的主要方法有兩種:

第一個是使用 InputProps 和 InputLabelProps:首先你可以創建一個 some.module.css 文件,你可以在其中創建你的類:

.input-border {
    border-color: #3E68A8 !important;
}

.inputLabel {
    color: #3E68A8 !important;
}

.helper-text {
    text-transform: initial;
    font-size: 1rem !important;
}

之后,您可以像這樣應用它們:

            <TextField
              sx={{
                textTransform: 'uppercase',
              }}
              FormHelperTextProps={{
                classes: {
                  root: classes['helper-text'],
                },
              }}
              InputProps={{
                classes: {
                  notchedOutline: classes['input-border'],
                },
              }}
              InputLabelProps={{
                classes: {
                  root: classes.inputLabel,
                  focused: classes.inputLabel,
                },
              }}
            />

請注意,上面還顯示了如何更改 FormHelperText 的顏色!

但是如果您有多個輸入字段,最好的方法是使用@mui/material/styles中的createTheme覆蓋您需要的組件

下面的示例顯示了一些組件,其余的您可以在開發工具中檢查,稍后在主題文件中只需 Ctrl + Space 將顯示所有可用的組件。 例子:

import { createTheme, responsiveFontSizes } from '@mui/material/styles';

const theme = createTheme({
  components: {
    // CTRL + SPACE to find the component you would like to override.
    // For most of them you will need to adjust just the root...
    MuiTextField: {
      styleOverrides: {
        root: {
          '& label': {
            color: '#3E68A8',
          },
          '& label.Mui-focused': {
            color: '#3E68A8',
          },
          '& .MuiInput-underline:after': {
            borderBottomColor: '#3E68A8',
          },
          '& .MuiOutlinedInput-root': {
            '& fieldset': {
              borderColor: '#3E68A8',
            },
            '&:hover fieldset': {
              borderColor: '#3E68A8',
              borderWidth: '0.15rem',
            },
            '&.Mui-focused fieldset': {
              borderColor: '#3E68A8',
            },
          },
        },
      },
    },
    MuiFormHelperText: {
      styleOverrides: {
        root: {
          textTransform: 'initial',
          fontSize: '1rem',
        },
      },
    },
  },
});

export default responsiveFontSizes(theme);


擴展彼得的答案 您也可以在沒有!important的情況下更改所有事件顏色:

 cssOutlinedInput: {
        "&:not(hover):not($disabled):not($cssFocused):not($error) $notchedOutline": {
          borderColor: "red" //default      
        },
        "&:hover:not($disabled):not($cssFocused):not($error) $notchedOutline": {
          borderColor: "blue" //hovered
        },
        "&$cssFocused $notchedOutline": {
          borderColor: "purple" //focused
        }
      },
      notchedOutline: {},
      cssFocused: {},
      error: {},
      disabled: {}

https://stackblitz.com/edit/material-ui-custom-outline-color-c6zqxp

這就是我解決我的問題的方法。

我想在專注時更改 TextField 的顏色。 如您所知,材料 Ui 文本字段聚焦時的默認顏色是藍色。 藍色是原色。

所以這里是 hack,我去了外部組件 App,然后定義了一個名為 createMuiTheme 的函數。 該函數返回一個名為pallet 的對象。 調色板內部是您提供顏色覆蓋的地方。 您將使用來自 materia ui 的 ThemeProvider 將新定義的顏色主題應用到您的應用程序,如下所示。 如需更多說明,請點擊此鏈接https://material-ui.com/customization/palette/

import {createMuiTheme, ThemeProvider} from '@material-ui/core';
import FormInput from './FormInput';

const theme = createMuiTheme({
  palette: {
    primary: {
      main: "your own color", //this overide blue color
      light: "your own color", //overides light blue
      dark: "your own color", //overides dark blue color
    },
  },
});


//apply your new color theme to your app component
function App(){
return(
<ThemeProvider theme={theme}> //applies custom theme
   <FormInput/>
</ThemeProvider>
)
}

這是我為 TextField 組件的懸停和聚焦狀態所做的。

MuiTextField: {
  styleOverrides: {
    root: {
      "& .MuiOutlinedInput-root:hover .MuiOutlinedInput-notchedOutline": {
        borderColor: "#ffb535",
      },
      "& .MuiOutlinedInput-root.Mui-focused  .MuiOutlinedInput-notchedOutline":
        {
          borderColor: "#ffb535",
        },
    },
  },
},

overrides 鍵使您能夠自定義組件類型的所有實例的外觀,... Material-Ui

在這種情況下,有一個簡短的答案,您必須使用 ThemeProvider 和 createMuiTheme

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

const theme = createMuiTheme({
  palette: {
    primary: {
      main: '#ff5722' //your color
    }
  }
});

function CustomTextfield(props) {
  return (
    <ThemeProvider theme={theme}>
      <TextField variant='outlined'/>
    </ThemeProvider>
  );
}

要進行更完整的自定義,您可以使用默認主題名稱palette 如果您不知道名稱或命名約定在哪里。 在樣式部分使用瀏覽器檢查器是您的救星,您可以注意到 css 鏈是如何在 material-ui 中制作的。

.MuiFilledInput-root {
position: relative;
transition: background-color 200ms cubic-bezier(0.0, 0, 0.2, 1) 0ms;
background-color: rgba(255,255,255,0.8);
border-top-left-radius: 4px;
border-top-right-radius: 4px;
}

MuiFilledInput > 根 > 背景顏色:

我們必須使用檢查器中的數據創建主題,我們只需將鏈放在覆蓋中:{}

const theme = createMuiTheme({
  overrides: {
    MuiFilledInput: {
      root: {
        backgroundColor: 'rgba(255,255,255,0.8)',
        '&:hover': {
          backgroundColor: 'rgba(255,255,255,1)'
        },
        '&.Mui-focused': {
          backgroundColor: 'rgba(255,255,255,1)'
        }
      }
    }
  }
});

現在您可以使用 ThemeProvider 進行覆蓋

import {
  createMuiTheme,
  ThemeProvider
} from '@material-ui/core/styles';

const theme = createMuiTheme({
  overrides: {
    MuiFilledInput: {
      root: {
        backgroundColor: 'rgba(255,255,255,0.8)',
        '&:hover': {
          backgroundColor: 'rgba(255,255,255,1)'
        },
        '&.Mui-focused': {
          backgroundColor: 'rgba(255,255,255,1)'
        }
      }
    }
  }
});

function CustomTextfield(props) {
  return (
    <ThemeProvider theme={theme}>
      <TextField variant='filled' />
    </ThemeProvider>
  );
}

因此,對於這個問題,您必須搜索自己的組件,因為名稱不同。

你可以像下面這樣覆蓋這種風格

/* for change border color*/
.MuiOutlinedInput-root.Mui-focused .MuiOutlinedInput-notchedOutline{
    border-color: #5EA841 !important;
}

/*for change label color in focus state*/
.MuiFormLabel-root.Mui-focused{
    color: #212121 !important;
}

你可以參考這段代碼:

樣式.js

cssLabel: {
  color : 'rgb(61, 158, 116) !important'
}, 
notchedOutline: {
  borderWidth: '1px',
  borderColor: 'rgb(61, 158, 116) !important',
  color: 'rgb(61, 158, 116)',
},

表單.js

<TextField
                name="creator"
                focused="true" 
                variant="outlined" 
                label="Creator"  
                fullwidth
                InputLabelProps={{
                    classes: {
                      root: classes.cssLabel,
                      focused: classes.cssLabel,
                    },
                }}
                InputProps={{
                    classes: {
                      root: classes.notchedOutline,
                      focused: classes.notchedOutline,
                      notchedOutline: classes.notchedOutline,
                    },
                    
                 }}
               
 />

基本上,您需要適當地設置 InputProps 的 notchedOutline 的邊框顏色。

下面是在MUI v5中使用styled()自定義邊框顏色的代碼。 生成的TextField有一個額外的borderColor屬性,可以讓你傳遞任何你想要的顏色,而不僅僅是來自 MUI 調色板的顏色。

import { styled } from '@mui/material/styles';
import MuiTextField from '@mui/material/TextField';

const options = {
  shouldForwardProp: (prop) => prop !== 'borderColor',
};
const outlinedSelectors = [
  '& .MuiOutlinedInput-notchedOutline',
  '&:hover .MuiOutlinedInput-notchedOutline',
  '& .MuiOutlinedInput-root.Mui-focused .MuiOutlinedInput-notchedOutline',
];
const TextField = styled(
  MuiTextField,
  options,
)(({ borderColor }) => ({
  '& label.Mui-focused': {
    color: borderColor,
  },
  [outlinedSelectors.join(',')]: {
    borderWidth: 3,
    borderColor,
  },
}));

用法

<TextField label="green" borderColor="green" />
<TextField label="red" borderColor="red" />
<TextField label="blue" borderColor="blue" />

Codesandbox 演示

在 MUI V5 中:

const theme = createTheme({
    
     components: {
        MuiInputBase: {
          styleOverrides: {
            root: {
              "&:before":{
                borderBottom:"1px solid yellow !imporatnt",}
            },
          },
        },
      },
    
    })

在 MUI V5 中,處理 styles 的最佳方式是通過 SX 屬性,如下例所示:

import * as React from 'react';
import TextField from '@mui/material/TextField';

// 1- Default styles
const rootStyles = {
  backgroundColor: '#ffd60a',
  border: '3px solid #001d3d',
};

const inputLabelStyles = {
  color: '#003566',
  textTransform: 'capitalize',
};

const rootInputStyles = {
  '&:hover fieldset': {
    border: '2px solid blue!important',
    borderRadius: 0,
  },
  '&:focus-within fieldset, &:focus-visible fieldset': {
    border: '4px solid red!important',
  },
};

const inputStyles = {
  color: 'red',
  paddingLeft: '15px',
  fontSize: '20px',
};

const helperTextStyles = {
  color: 'red',
};

export default function InputField({
  label = 'default label',
  // 2- User custom styles
  customRootStyles,
  customInputLabelStyles,
  customRootInputStyles,
  customInputStyles,
  customHelperTextStyles,
}) {
  return (
    <TextField
      label={label}
      helperText="Please enter a valid input"
      sx={{ ...rootStyles, ...customRootStyles }}
      InputLabelProps={{
        sx: {
          ...inputLabelStyles,
          ...customInputLabelStyles,
        },
      }}
      InputProps={{
        sx: {
          ...rootInputStyles,
          ...customRootInputStyles,
        },
      }}
      inputProps={{
        sx: {
          ...inputStyles,
          ...customInputStyles,
        },
      }}
      FormHelperTextProps={{
        sx: {
          ...helperTextStyles,
          ...customHelperTextStyles,
        },
      }}
    />
  );
}

要了解有關其工作原理的更多信息,您可以通過此鏈接查看原始文章。

我的意思是Mui.TextField有3種風格:標准,填充,概述。 以上解決方案僅適用於概述的樣式

這里是一個選擇輸入的例子:

import {
  FormControl,
  InputLabel,
  Select,
  MenuItem,
  OutlinedInput as MuiOutlinedInput,
} from "@material-ui/core";
    
const OutlinedInput = withStyles((theme) => ({
  notchedOutline: {
    borderColor: "white !important",
  },
}))(MuiOutlinedInput);

const useStyles = makeStyles((theme) => ({
  select: {
    color: "white",
  },
  icon: { color: "white" },
  label: { color: "white" },
}));

function Component() {
  return (
    <FormControl variant="outlined">
      <InputLabel id="labelId" className={classes.label}>
        Label
      </InputLabel>
      <Select
        labelId="labelId"
        classes={{
          select: classes.select,
          icon: classes.icon,
        }}
        input={<OutlinedInput label="Label" />}
      >
        <MenuItem>A</MenuItem>
        <MenuItem>B</MenuItem>
      </Select>
    </FormControl>
  );
}

對我來說,我不得不使用純 CSS:

.mdc-text-field--focused .mdc-floating-label {
  color: #cfd8dc !important;
}
.mdc-text-field--focused .mdc-notched-outline__leading,
.mdc-text-field--focused .mdc-notched-outline__notch,
.mdc-text-field--focused .mdc-notched-outline__trailing {
  border-color: #cfd8dc !important;
}

// optional caret color
.mdc-text-field--focused .mdc-text-field__input {
  caret-color: #cfd8dc !important;
}

Ĵ

借助classes屬性,您可以覆蓋 Material-UI 注入的所有類名。 查看覆蓋類部分和組件的實現以獲取更多詳細信息。

最后:

Input React 組件的 API 文檔。 了解有關屬性和 CSS 自定義點的更多信息。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM