如何使用React覆盖默认的MaterialUI样式?

时间:2019-07-11 23:37:48

标签: css reactjs material-ui

在将Material UI与React一起使用时,我无法使用想要的属性来对Outline Select组件进行样式设置,如何覆盖默认样式?

我使用过withStyles,但无法达到预期的外观。 例如,如果我使用“选择”中的自定义“输入”来更改边框,则“标签”将无法按预期工作,边框和标签会接触,而不是像浮动图标一样贴标签。

import { createStyles, makeStyles, withStyles } from '@material-ui/core/styles';
import OutlinedInput from '@material-ui/core/OutlinedInput';
import InputLabel from '@material-ui/core/InputLabel';
import MenuItem from '@material-ui/core/MenuItem';
import FormControl from '@material-ui/core/FormControl';
import Select from '@material-ui/core/Select';

export const StyledSelect = ({ name, value, onChange, items }) => {
  const classes = useStyles();
  const inputLabel = React.useRef<HTMLLabelElement>(null);
  const [labelWidth, setLabelWidth] = React.useState(0);

  React.useEffect(() => {
    setLabelWidth(inputLabel.current!.offsetWidth);
  }, []);
  return (
    <FormControl variant="outlined" />
      <InputLabel
        ref={inputLabel}
        htmlFor={name}
      >
        {name}
      </InputLabel>
      <Select
        value={value || ''}
        onChange={onChange}
        input={<CustomInput labelWidth={labelWidth} />}
      >
        {items.map(item => {
          return (
            <MenuItem key={item.key} value={item}>
              {item.label}
            </MenuItem>
          );
        })}
      </Select>
    </FormControl>
  );
};


const CustomInput = withStyles(theme => ({
  root: {
    'label + &': {
      /* marginTop: theme.spacing(3), */
    },
  },
  /* label: {
    width: '',
  }, */
  input: {
    'borderRadius': 4,
    'position': 'relative',
    /* 'backgroundColor': theme.palette.background.paper, */
    'border': '2px solid #ced4da',
    /* 'fontSize': 16, */
    /* 'transition': theme.transitions.create(['border-color', 'box-shadow']), */
    // Use the system font instead of the default Roboto font.
    'fontFamily': [
      '-apple-system',
      'BlinkMacSystemFont',
      '"Segoe UI"',
      'Roboto',
      '"Helvetica Neue"',
      'Arial',
      'sans-serif',
      '"Apple Color Emoji"',
      '"Segoe UI Emoji"',
      '"Segoe UI Symbol"',
    ].join(','),
    '&:hover': {
      border: '2px solid red',
      borderRadius: 4,
    },
    '&:focus': {
      border: '2px solid #ced4da',
      borderRadius: 4,
      borderRadius: 4,
      borderColor: "#80bdff",
      boxShadow: "0 0 0 0.2rem rgba(0,123,255,.25)"
    },
  },
}))(OutlinedInput);

我希望只设置所需样式,并且不会破坏OutlineSelect组件的功能。

1 个答案:

答案 0 :(得分:0)

在材质用户界面中单击输入字段时,类名称将更改,并且label field会采用不同的样式。

更具体地说,将类.MuiInputLabel-shrink添加到了label元素。如果要定位此样式,则必须在withStyles()

中引用该类

在此处查看imput-label API: https://material-ui.com/api/input-label/#main-content

相关问题