简体   繁体   中英

How to override MUI 5 input label background color for custom component

I've been struggling on how to override the background color for a MUI 5 input label on focus for a specific component. I was able to override the background color and set it to blue in my _theme.js file but this change is global. Does anyone know how I would override this and make the background color red for my KeywordSearchTextField in my index.js file following MUI 5 best practice? Any help is greatly appreciated! Please see my sandbox at https://codesandbox.io/s/mui-5-styling-uqt9m?file=/pages/index.js . Code snippet below...

import Box from "@mui/material/Box";
import TextField from "@mui/material/TextField";
import Autocomplete from "@mui/material/Autocomplete";
import { styled, createTheme, useTheme } from "@mui/material/styles";

const styles = {
  baseBoxStyle: {
    maxWidth: "350px",
    margin: "20px",
    padding: "10px"
  }
};

const KeywordSearchContainer = styled("div")(() => ({}));

const KeywordSearchTextField = styled(TextField)(() => ({}));

const keywordOptions = [
  { label: "Generic keyword 1", value: "Generic keyword 1" },
  { label: "Generic keyword 2", value: "Generic keyword 2" },
  { label: "Generic keyword 3", value: "Generic keyword 3" }
];

export default function Index() {
  return (
    <Box sx={{ ...styles.baseBoxStyle }}>
      <KeywordSearchContainer>
        <Autocomplete
          id="free-solo-demo"
          options={keywordOptions.map((option) => option.label)}
          renderInput={(params) => (
            <KeywordSearchTextField
              {...params}
              label="freeSolo"
              InputLabelProps={{
                classes: {
                  focused: "focused"
                }
              }}
            />
          )}
        />
      </KeywordSearchContainer>
    </Box>
  );
}```

Add your styles to a targeted nested class (componet-slot combo) like so: See also my forked codesandbox

<KeywordSearchTextField
  {...params}
  sx={{
    '& .MuiInputBase-input:focus': {
      backgroundColor: 'red',
    },
  }}
  label="freeSolo"
  InputLabelProps={{
    classes: {
      focused: 'focused',
    },
  }}
/>

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