【问题标题】:How to change the border color of MUI TextField如何更改 MUI TextField 的边框颜色
【发布时间】:2019-03-25 10:56:10
【问题描述】:

我似乎不知道如何更改轮廓变体的轮廓颜色TextField

我查看了 GitHub 问题,人们似乎指向使用 TextField "InputProps" 属性,但这似乎无济于事。

这是我当前状态的代码

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

【问题讨论】:

    标签: reactjs material-ui jss


    【解决方案1】:

    看看这个,我做了一个快速演示:

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

    它改变了Material-UI TextField的默认边框颜色和标签颜色,但在聚焦时保持原色。

    另外,看看这个链接,它给了我“想法”:

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

    如果您想在聚焦时更改颜色,请查看文档中的这些示例:

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

    【讨论】:

    • 啊,在某些情况下你仍然需要 !important。谢谢!
    • 试图让它与createMuiTheme一起工作,有什么想法吗?
    • 标签颜色onfocus没有改变,怎么改变?
    • 你必须添加 !important,可能不好。
    【解决方案2】:

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

    【讨论】:

    • 注意:TextField 必须有 variant='outlined'
    • 这必须是公认的答案。我到处搜索后发现了这个。谢谢。
    【解决方案3】:
    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"
                />
    

    【讨论】:

    • 这个答案对我有帮助,但我不需要 !important 部分。 Material-UI 4.11.2版
    【解决方案4】:

    如果有人想用 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;
        }
      }
    `;
    

    我花了很长时间才弄明白。希望它可以帮助某人。

    【讨论】:

    • 你能解释一下为什么&amp; label.Mui-focused中的和号后面有一个空格而&amp;.Mui-focused fieldset中没有空格吗?
    【解决方案5】:

    Textfield 边框的问题是你要设置的颜色 specificity 比 Material-UI (MUI) 设置的原始样式低。

    例如MUI 在聚焦时设置此类:

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

    这比自定义选择器更具体,例如:

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

    解决方案 A (不推荐)

    您可以将!important 异常添加到颜色,但这是'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,
                },
            } }
        /> );
    });
    

    解决方案 B (推荐)

    official MUI example 使用其他方式来增加特异性。

    “诀窍”是不要直接设置元素的样式,例如:

    .someChildElement { border-color: #f0f }
    

    但要添加一些额外的选择器(比 MUI 更多*),例如:

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

    *(实际上使用与 MUI 相同的选择器就足够了, 因为如果选择器的特异性相同, 然后使用“后来的”)

    包含父元素:您可能已经注意到设置notchedOutline确实为未聚焦的元素设置颜色,但不为聚焦的元素设置颜色。 这是因为 MUI 样式包含输入框的 parent 元素 (.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 发明以来唯一的解决方案,因此它被认为是可以接受的

    【讨论】:

    • 使用空格&或不使用空格&有什么区别
    • 这基本上是SASS 语法:&amp;.myClass vs. &amp; .myClass 就像span.myClass vs. span .myClass。 (我在答案中的代码中添加了注释。)
    【解决方案6】:
      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 样式适用于文本文件的外部部分...

    material UI 的外部样式在上面要求更改...

    【讨论】:

      【解决方案7】:

      使用它覆盖 CSS 属性

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

      【讨论】:

        【解决方案8】:

        扩展彼得的answer。您也可以在没有 !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】:

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

          如需更完整的自定义,您可以使用默认主题名称pallete。 如果您不知道名称或命名约定在哪里。 在 style 部分使用 de browser inspector 是你的救星,你可以注意到 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 > root > 背景颜色:

          我们必须使用检查器中的数据创建主题,我们只需将链放在覆盖中:{}

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

          所以对于这个问题,你必须搜索自己的组件,因为有不同的名称。

          【讨论】:

          • 你从哪里找到这个 MuiFilledInput 键,我怎样才能找到其他组件的这些?
          【解决方案10】:

          这就是我的解决方法。

          我想在专注时更改 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>
          )
          }
          

          【讨论】:

            【解决方案11】:

            对于最新的 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 的颜色!

            但如果您有多个输入字段,最好的方法是使用 createTheme from @mui/material/styles 覆盖您需要的组件

            下面的示例显示了一些组件,其余的您可以在开发工具中检查,稍后在主题文件中只需 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);
            
            
            

            【讨论】:

              【解决方案12】:

              你可以参考这段代码:

              styles.js

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

              form.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 的边框颜色。

              【讨论】:

                【解决方案13】:

                这里是一个选择输入的例子:

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

                【讨论】:

                  【解决方案14】:

                  下面是在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" />
                  

                  【讨论】:

                    【解决方案15】:

                    在 MUI V5 中:

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

                    【讨论】:

                      【解决方案16】:

                      你可以像下面这样覆盖这个样式

                      /* 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;
                      }
                      
                      

                      【讨论】:

                        【解决方案17】:

                        借助 classes 属性,您可以覆盖 Material-UI 注入的所有类名。 请查看overriding with classes 部分和implementation of the component 了解更多详情。

                        最后:

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

                        【讨论】:

                        • 您能否就问题中的案例举一个具体的例子?如何改变边框的颜色?
                        • 不知道为什么会有这么多反对票。是的,它没有解释如何修改颜色,但它确实公开了修改样式的方法,其中包括颜色。它也不是复制和粘贴、仅代码或仅链接的答案。并且它被 OP 接受了,但有反对票吗?这使 OP 不仅仅可以修改颜色。因为这篇文章,人们将更加熟悉整个系统,避免潜在的关于样式的重复问题。如果他们愿意,其他答案可以随意喂食,但这个答案对社区仍然非常有用。这就是人们放弃的原因...
                        • @Dioxin 这个答案没有提供很多价值,我敢打赌,任何人都可以轻松地在文档中找到该信息。但是,我不同意投反对票的答案,尤其是像这样的答案,因为它仍然可以增加价值,而投反对票会阻碍发帖者。如果人们认为还有其他更好的答案,那么他们应该投票赞成。
                        • @ehab Jojo 有 32 个赞,他们所做的只是粘贴代码而没有解释。仅仅因为 OP 没有提供他可以复制和粘贴的代码示例,并不意味着没有提供价值。 OP接受了它。我不会怀疑反对者来自想要复制和粘贴答案的人。
                        • @Dioxin 这不是一种或另一种方式。复制粘贴代码和“rtfm”之间存在巨大的灰色区域。 MUI 表单元素的样式细微差别是一个很好的例子,即使在阅读了文档之后也具有挑战性。当然,任何好的答案(或问题)都应该突出相关文档,但是当您阅读文档和 GH 问题并尝试认真应用它们但没有成功时,讨论什么有效和什么无效的特定怪癖是非常有价值的。 Docs 并不总是完美的,OP 也不是唯一一个可能尝试过但失败的人。
                        猜你喜欢
                        • 2019-12-23
                        • 2019-11-23
                        • 1970-01-01
                        • 1970-01-01
                        • 2021-12-07
                        • 2018-10-11
                        • 1970-01-01
                        • 1970-01-01
                        • 2019-06-29
                        相关资源
                        最近更新 更多