How to change the border color of Material-UI <TextField/>

假装没事ソ 提交于 2020-11-30 04:49:33

问题


I can't seem to figure out how to change the outline color of an outlined variant I looked around GitHub issues and people seem to be pointing towards using the "InputProps" Property but this seems to do nothing. Here is my code in its current 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);

回答1:


You can override all the class names injected by Material-UI thanks to the classes property. Have a look at overriding with classes section and the implementation of the component for more detail.

and finally :

The API documentation of the Input React component. Learn more about the properties and the CSS customization points.




回答2:


Take a look at this, I made a quick demo:

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

It changes the default border color and the label color of the Material-UI TextField but keeps the primary color when focused.

Also, take a look at this link, it gave me the "idea":

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

If you want to change the color when focused look at these examples from the documentation:

https://material-ui.com/demos/text-fields/#customized-inputs




回答3:


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'}}}

                    />

//declare the const and add the material UI style

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);



回答4:


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"
            />




回答5:


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

The Inputprops works by styling the enterd input data in the textfield and also we can use className for custom coloring..

      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',
     },
     },
    },

This const style works the outer potion of the text filed...

The styling of the outer portion of material UI is above asked for change...




回答6:


In case anyone wants to do this with styled-components:

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;
    }
  }
`;

This took me WAY too long to figure out. Hope it helps someone.




回答7:


use this overrides CSS property

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




回答8:


Extending Peter's answer. You could also change all event colors without the !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




回答9:


The overrides key enables you to customize the appearance of all instances of a component type,... Material-Ui

In this case there is a short answer, you have to use ThemeProvider and 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>
  );
}

For a more complete customization you can use the default theme names pallete. If you dont know where are the names or naming conventions. Using de browser inspector in the style section is your savior, you can notice how the css chain is made in 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 > root > background-color:

we have to create de theme using the data from the inspector, we only have to place the chain in overrides:{}

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)'
        }
      }
    }
  }
});

Now you can make the override using 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>
  );
}

So for this question you have to search your own components, because have different names.




回答10:


The Problem with the Textfield border is that the color you want to set has a lower specificity than the original style that Material-UI (MUI) sets.

E.g. MUI sets this class when focused:

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

which is more specific than a custom selector like:

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

Solution A (not recommended)

You can add the !important exception to the color, but this is 'bad practice':

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,
            },
        } }
    /> );
});

Solution B (recommended)

The official MUI example and many tutorials use other ways to increase specificity. (Which are mostly not explained and do not work as-is under all circumstances.)

The 'trick' is not to style the Element directly, like:

.someChildElement { border-color: #f0f }

but to add some extra selectors (more than MUI does*), e.g.:

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

*(Actually it is enough to use the same selectors as MUI does, because if specificity of the selectors is the same, then the 'later' ones are used)

Include the parent: You might have noticed that setting notchedOutline does set the color for the un-focused element, but not for the focused. That is because the MUI style includes the parent element of the input box (.MuiOutlinedInput-root.Mui-focused). So you need to include the parent as well.

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)
        '& .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 }
    />);
})

Note that you can increase specificity in different ways, e.g. this would work as well (a bit different):

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

Remark: It might seem a little bit 'dirty' to add selectors only to increase specificity, when you don't really 'need' them. I think it is, but this workaround was sometimes the only solution since CSS was invented, so it is considered kind of acceptable.



来源:https://stackoverflow.com/questions/52911169/how-to-change-the-border-color-of-material-ui-textfield

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!