繁体   English   中英

更改材质 UI 选择组件边框的颜色不起作用

[英]Change color of Material UI Select component border not working

我正在使用 material-ui v5 进行学习。 我在覆盖 mui Select 组件的默认样式时遇到了困难。 我想在将鼠标悬停在 Select 上并处于聚焦状态时更改其颜色。 目前,聚焦状态的颜色是这样的。

在此处输入图像描述

这是我的代码:

import { useState, useEffect } from 'react';
import { makeStyles } from '@mui/styles';
import { Select, MenuItem } from '@mui/material';

const useStyles = makeStyles({
    select: {
     '&.MuiOutlinedInput-root': {
       width: '200px'
     },
    '& .MuiOutlinedInput-notchedOutline': {
        borderColor: 'red',
          '&:hover': {
          borderColor: 'green'
        }
     },

    }
})

function App() {
  const classes = useStyles();
  const [age, setAge] = useState('');

  const handleChange = (event: SelectChangeEvent) => {
    setAge(event.target.value);
  };
  return (
        <Select
          variant="outlined"
          className={classes.select}
          labelId="demo-simple-select-label"
          id="demo-simple-select"
          value={age}
          label="Age"
          onChange={handleChange}
        >
          <MenuItem value={10}>Ten</MenuItem>
          <MenuItem value={20}>Twenty</MenuItem>
          <MenuItem value={30}>Thirty</MenuItem>
        </Select>
  );
}

export default App;

任何帮助将不胜感激。

首先:

@mui/styles 是 MUI 的传统样式解决方案。 它依赖于 JSS 作为样式解决方案,它不再在 @mui/material 中使用,在 v5 中已弃用。 如果您不想在包中同时包含情感和 JSS,请参阅@mui/system 文档,这是推荐的替代方法。

你可以在这里查看更多。 因此,对于自定义,您可能应该使用styled-components

MUI中的Select组件在其后面使用输入字段,并且要完成您需要自定义input的内容,这就是您使用.MuiOutlinedInput-root类的原因。 因此, MUI这里有一些input自定义示例。

这是一个自定义Select示例:

const CustomSelect = styled(Select)(() => ({
  width: 300,
  "&.MuiOutlinedInput-root": {
    "& fieldset": {
      borderColor: "red"
    },
    "&:hover fieldset": {
      borderColor: "yellow"
    },
    "&.Mui-focused fieldset": {
      borderColor: "green"
    }
  }
}));

使用新的样式 API“styled”,您可以通过使用 mui 提供的类对象导入来实现您想要的自定义级别。 我说过重要的是不要在“&”和“。”之间留下空格。 在css中,否则将不起作用,测试它! 在此示例中,我正在使用 :hover 选择器自定义 Select 的边框颜色,并使用来自组件的焦点类处于焦点状态。 最后,选择被声明为 notchedOutlined,因此使用了类。

 import {
  Select,
  outlinedInputClasses,
  selectClasses
} from '@mui/material';
import { styled } from '@mui/system';

export const StyledSelect = styled(Select)`
  width: 150px;
  height: 40px;
  color: #fff;
  border-color: #fff;

  & .${selectClasses.icon} {
    color: #fff;
  }

  & .${outlinedInputClasses.notchedOutline} {
    border-color: #fff;
  }
  &:hover .${outlinedInputClasses.notchedOutline} {
    border-color: #fff;
  }

  &.${outlinedInputClasses.focused} .${outlinedInputClasses.notchedOutline} 
  {
    // VERY IMPORTANT TO NOT LEAVE AN EMPTY SPACE BETWEEN '&' AND '.'
    border-color: #fff !important;
  }
`;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM