如何在 material ui 中设置输入样式

How to style Input in material ui

我是 material ui 的新手。

我用的是第五版

            <InputBase
              ref={params.InputProps.ref}
              inputProps={params.inputProps}
              autoFocus
              sx={{
                ...InputCSS,
              }}
            />


const InputCSS = {
  width: '100%',
  textIndent: '17px',
  py: '12px',
  fontSize: '20px',
  borderRadius: '3px',
  border: '1.5px solid rgba(0, 0, 0, 0.4)',
  'MuiInputBase-root': { // does not work
    borderColor: 'red !important',
    color: 'red !important',
  },
  '&:focus' : { // does not work
     ...
   }
}

我本可以使用 styled('input') 并且它有效,我可以设置 &:focus 并且它有效但我无法在输入中键入任何内容。

我想摆脱初始边框并设置焦点属性。

如何更改此 class 的边框?

我知道在 v5 中我们可以使用 variants 或 sx 或 styled 来设计我们的组件。

样式化 mui 组件的最佳建议是什么?因为互联网上几乎所有信息都使用过时的 useStyle 或 makeStyles,它们不适用于 React 18v。

有时我只是为 mui

中的组件样式而苦恼

您可以通过多种方式自定义 Mui 组件,但我最喜欢的三种方式是:

  1. 样式实用程序
  2. Sx 道具
  3. 自定义全局主题

那么我应该什么时候使用这些方法?

样式实用程序

如果你想让一个组件在你的应用程序中重复使用,请选择 styled,如果你曾经使用过 styled components 那么 styled 对你来说会非常熟悉,这里是如何使用它的示例:

import * as React from 'react';
import Slider, { SliderProps } from '@mui/material/Slider';
import { alpha, styled } from '@mui/material/styles';

// if you are using typescript, don't forget to pass the component props on styled
const SuccessSlider = styled(Slider)<SliderProps>(({ theme }) => ({
  width: 300,
  color: theme.palette.success.main,
  // to override the styles of inner elements, 
 // you have to use the & selector followed by the class name.
  '&.MuiSlider-thumb': {
    '&:hover, &.Mui-focusVisible': {
      boxShadow: `0px 0px 0px 8px ${alpha(theme.palette.success.main, 0.16)}`,
    },
    '&.Mui-active': {
      boxShadow: `0px 0px 0px 14px ${alpha(theme.palette.success.main, 0.16)}`,
    },
  },
}));

export default function StyledCustomization() {
  return <SuccessSlider defaultValue={30} />;
}

为了使组件更加动态,您还可以定义自定义属性,如宽度、颜色、边框等,read the styled docs了解更多。

Sx 道具

如果你想在单个组件中制作一次性样式,最简单的方法是使用 sx prop,但要小心使用这种方法,因为它会导致你的代码中出现大量重复代码。按照您提供的代码:

<InputBase
   ref={params.InputProps.ref}
   inputProps={params.inputProps}
   autoFocus
   sx={{
   ...InputCSS,
   }}
/>

const InputCSS = {
  width: '100%',
  textIndent: '17px',
  py: '12px',
  fontSize: '20px',
  borderRadius: '3px',
  border: '1.5px solid rgba(0, 0, 0, 0.4)',
  // you should pass the & selector followed by the class that you want to override
  '&.MuiInputBase-root': {
  // avoid the use of !important
    borderColor: 'red',
    color: 'red',
  },
  '&.MuiInputBase-root:focus': {
     ...
   }
}

check it out 在 codeSandbox 上。只是一个建议,根据您的情况,组件 TextField 可能更适合,因为它带有一些很好的样式,您不需要从头开始设置它的样式。

旁注:

每个 mui 组件都有一个带有 css 部分的 api 文档,您可以在其中找到所有可用的 类 来覆盖,例如, 请参阅 InputBase api docs, also read the docs about sx prop.

自定义主题

最后但同样重要的是,如果你想使用自定义调色板、组件、排版、断点等来自定义你的整个应用程序,毫无疑问你应该使用自定义主题,因为 mui 提供了一个名为 createTheme 这样做,我最喜欢自定义主题的是可以自定义组件的 variants,像这样:

import * as React from "react";
import { createTheme, ThemeProvider } from "@mui/material/styles";
import Button from "@mui/material/Button";
import { red } from "@mui/material/colors";

 // if you are using typescript, you must declare the module with the 
// custom properties in order to get access of this property when using the component
declare module "@mui/material/Button" {
  // define custom variants
  interface ButtonPropsVariantOverrides {
    dashed: true;
    redVariant: true;
  }
}

const defaultTheme = createTheme();

const theme = createTheme({
  components: {
    MuiButton: {
      variants: [
        {
          // use the variant name defined earlier
          props: { variant: "dashed" },
          // set the styles for this variant
          style: {
            textTransform: "none",
            border: `2px dashed ${defaultTheme.palette.primary.main}`,
            color: defaultTheme.palette.primary.main
          }
        },
        {
          props: { variant: "redVariant" },
          style: {
            border: `2px solid ${red[300]}`,
            color: red[600]
          }
        }
      ]
    }
  }
});

export default function GlobalThemeVariants() {
  return (
    // use the theme provider to get access of custom theme
   // and variants within any child component
    <ThemeProvider theme={theme}>
      <Button variant="dashed" sx={{ m: 1 }}>
        Dashed
      </Button>
      <Button variant="redVariant" color="secondary">
        custom red variant
      </Button>
    </ThemeProvider>
  );
}

参见the example, also take a look at the custom theme docs。希望我把事情弄清楚了一点!