【问题标题】:How to override MUI 5 input label background color for custom component如何覆盖自定义组件的 MUI 5 输入标签背景颜色
【发布时间】:2022-01-22 21:20:01
【问题描述】:

我一直在努力解决如何覆盖特定组件焦点上的 MUI 5 输入标签的背景颜色。我能够在我的 _theme.js 文件中覆盖背景颜色并将其设置为蓝色,但此更改是全局的。有谁知道我将如何覆盖它并按照 MUI 5 最佳实践将我的 index.js 文件中的 KeywordSearchTextField 的背景颜色设为红色?任何帮助是极大的赞赏!请在https://codesandbox.io/s/mui-5-styling-uqt9m?file=/pages/index.js 查看我的沙箱。下面的代码sn-p...

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>
  );
}```

【问题讨论】:

    标签: javascript reactjs material-ui


    【解决方案1】:

    将您的样式添加到目标nested 类(组件插槽组合),如下所示: 另见我的分叉codesandbox

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

    【讨论】:

    • 非常感谢山姆!奇迹般有效。仅供参考,我试图仅更改标签背景颜色并最终使用下面的样式,但您的答案正是我想要的。再次感谢! sx={{ '& .MuiInputLabel-root': { '&.Mui-focused': { backgroundColor: 'red', } }, }}
    猜你喜欢
    • 1970-01-01
    • 2012-12-26
    • 1970-01-01
    • 1970-01-01
    • 2019-07-18
    • 1970-01-01
    • 1970-01-01
    • 2013-02-09
    • 1970-01-01
    相关资源
    最近更新 更多