首页 > 解决方案 > React Material UI - Override using withStyles

问题描述

I am working on a project and leverage React Material UI and need to override the Select component's border bottom color on the focused state. Here is what I'm using right now

import { Select as MuiSelect, withStyles } from '@material-ui/core';
import { BRAND_COLORS } from '../../constants/colors';

const FONT_SIZE = 20;

const Select = withStyles({
  root: {
    fontSize: FONT_SIZE,
    '&:focus': {
      backgroundColor: 'transparent',
    },
    '& .MuiInput-underline:after': {
      borderBottomColor: BRAND_COLORS.blue,
    },
  },
})(MuiSelect);

export default Select;

<Select
  native
  startAdornment={<InputAdornment position="start"><FilterListIcon /></InputAdornment>}
  value={service.regionalFocus}
  onChange={(event) => this.props.changeSelectedRegionalFocus({
      providerId, serviceId: service.service_id, regionalFocus: 
event.target.value})
      }
    >
      {regionalFocus.map((region, index) => service.service_regions[region.value].length ? (
        <option key={index} value={region.value}>
          {region.label}
        </option>
      ) : null)}
    </Select>

I'm able to override the font size, however, the borderBottomColor is not registering. Any thoughts?

标签: reactjsmaterial-uireact-with-styles

解决方案


看起来您正在尝试InputSelect. 要覆盖道具Input,包括样式,您需要将它们作为覆盖传递给.inputPropsSelect

就像是:

const MySelect = (props) => {
  return (
    <Select {...props} inputProps={{ classes: { underline: props.classes.inputOverride } }}
  );
};

export default withStyles({
  root: {
    fontSize: FONT_SIZE,
    '&:focus': {
      backgroundColor: 'transparent',
    }
  },
  inputOverride: {
    '&:after': {
      borderBottomColor: BRAND_COLORS.blue,
    }
  }
})(MySelect);

文档将在此处为您提供帮助: Selecthttps ://material-ui.com/api/select/ https://material-ui.com/api/input/Input

以及真正了解它是如何工作的源代码: https ://github.com/mui-org/material-ui/blob/d956b40539d7b724ca6026aeae96e1f42dd22331/packages/material-ui/src/Select/Select.js#L230


推荐阅读