繁体   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