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

Ros*_*tyk 2 reactjs 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
     ...
   }
}
Run Code Online (Sandbox Code Playgroud)

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

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

如何更改该类的边框?

在此输入图像描述

我知道在 v5 中我们可以使用变体或 sx 或 styled 来设置组件的样式。

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

有时我只是在 mui 中的组件样式上遇到困难

Yag*_*ann 8

您可以通过多种方法来自定义 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} />;
}
Run Code Online (Sandbox Code Playgroud)

为了使组件更加动态,您还可以定义自定义属性,例如宽度、颜色、边框等,请阅读样式文档以了解更多信息。

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': {
     ...
   }
}
Run Code Online (Sandbox Code Playgroud)

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

边注:

每个 mui 组件都有一个带有css部分的 api 文档,您可以在其中找到要覆盖的所有可用类,例如,请参阅InputBase api 文档,还可以阅读有关 sx prop 的文档

自定义主题

最后但并非最不重要的一点是,如果您想使用自定义调色板、组件、排版、断点等来自定义整个应用程序,毫无疑问您应该使用自定义主题,因为 mui 提供了一个强大的工具来执行此操作createTheme,这是我喜欢的自定义主题中最重要的是可以制作组件的自定义变体,如下所示:

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>
  );
}
Run Code Online (Sandbox Code Playgroud)

请参阅示例,另请参阅自定义主题文档。希望我能澄清一些事情!

  • 非常感谢,非常详细,很有帮助!!! (2认同)