简体   繁体   中英

Unable to change border color when focused and not focused of Material UI Input

I'm not sure why I can't get this to work. I'm selecting the MuiInputBase-root element, telling it to select the field and set the border color to blue, and on focus set the border color to red. What am I doing wrong here?

Codesandbox

import React from "react";
import "./styles.css";

import { makeStyles } from "@material-ui/core/styles";
import FormControl from "@material-ui/core/FormControl";
import OutlinedInput from "@material-ui/core/OutlinedInput";
import InputLabel from "@material-ui/core/InputLabel";

const useStyles = makeStyles(theme => ({
  root: {
    width: "20rem"
  },
  label: {
    background: "white",
    paddingRight: theme.spacing(0.5),
    "&.Mui-focused": {
      color: theme.palette.secondary.main
    }
  },
  closeIcon: {
    color: theme.palette.grey[400],
    "&.hidden": {
      display: "none"
    }
  },
  searchIcon: {
    color: theme.palette.primary.main
  }
}));

const useOutlinedInputStyles = makeStyles({
  root: {
    "& .MuiInputBase-root": {
      "& fieldset": {
        borderColor: "blue"
      },
      "&.Mui-focused fieldset": {
        borderColor: "red"
      }
    }
  }
});

export default function App() {
  const classes = useStyles();
  const outlinedInputStyles = useOutlinedInputStyles();
  return (
    <div className="App">
      <FormControl className={classes.root} variant="outlined">
        <InputLabel className={classes.label} htmlFor="search-input">
          placeholder
        </InputLabel>
        <OutlinedInput
          classes={outlinedInputStyles}
          id="search-input"
          labelWidth={70}
        />
      </FormControl>
    </div>
  );
}

图像

The issue is that the .MuiInputBase-root is not a child of the root element (the .MuiOutlinedInput-root element), it's actually exactly the same element, so that layer is unnecessary. Also, type selectors (eg fieldset ) have lower specificity than class selectors, so &.Mui-focused fieldset does not have sufficient specificity to override the default focused styles . Instead of fieldset you can use the class selector .MuiOutlinedInput-notchedOutline .

So instead of:

root: {
  "& .MuiInputBase-root": {
    "& fieldset": {
      borderColor: "blue"
    },
    "&.Mui-focused fieldset": {
      borderColor: "red"
    }
  }
}

You should have:

  root: {
    "& .MuiOutlinedInput-notchedOutline": {
      borderColor: "blue"
    },
    "&.Mui-focused .MuiOutlinedInput-notchedOutline": {
      borderColor: "red"
    }
  }

编辑 OutlinedInput 边框

Related answer: Change border color on Material-UI TextField

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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