如何在MUI样式HTML元素标签?



我使用的是最新的MUI版本(v5)和@mui/materials的CssBaseline,并给出了我通常如何在CSS中做到这一点:

body, html, #root {
width: 100%;
height: 100%;
min-height: 100%;
margin: 0;
padding: 0;
font-size: 62.5%; /* makes 1.2rem === 12px, 1.6rem === 16px, ect... */
text-align: left;
}

梅身体

(将以下内容添加到my theme中)

components: {
MuiCssBaseline: {
styleOverrides: {
body: {
width: '100%',
height: '100%',
minHeight: '100%',
margin: 0,
padding: 0,
fontSize: '62.5%', // makes 1.2rem === 12px, 1.6rem === 16px, ect...
textAlign: 'left'
}
}
}
}

梅根

(添加以下到我的sxStyle,例如:sx={{...sxLayout, ...sxLayout.root}})

const sxLayout = {
flexDirection: 'column',
root: {
width: '100%',
height: '100%',
minHeight: '100%',
margin: 0,
padding: 0,
fontSize: '62.5%', // makes 1.2rem === 12px, 1.6rem === 16px, ect...
textAlign: 'left',
'&': {
width: '100%',
height: '100%',
minHeight: '100%',
margin: 0,
padding: 0,
fontSize: '62.5%', // makes 1.2rem === 12px, 1.6rem === 16px, ect...
textAlign: 'left'
},
'&.MuiListItemButton-root': {
width: '100%',
height: '100%',
minHeight: '100%',
margin: 0,
padding: 0,
fontSize: '62.5%', // makes 1.2rem === 12px, 1.6rem === 16px, ect...
textAlign: 'left'
}
}
}

梅Html

(? ?)
????

有几种方法可以为组件设置样式。我描述的最后一个是特定于MUI的,并且最有可能是您正在寻找的。

一些css类属于特定的MUI组件,所以你只使用MUI组件,如果你的<ThemeProvider />被正确使用,你不应该添加任何类。

您可以选择在单独的文件中定义常规CSS或SASS,并将其导入到组件中,然后通过组件的className属性使用该类。

另一个选项是CSS-in-JS。你可以使用style属性来使用自定义css,并在你的JS文件中为组件定义css:

... //inside your component
const mystyle = {
color: "white",
backgroundColor: "DodgerBlue",
padding: "10px",
fontFamily: "Arial"
};
...
return (
<div>
<h1 style={mystyle}>Hello Style!</h1>
<p>Add a little style!</p>
</div>
);
...

以上例子改编自https://www.w3schools.com/react/react_css.asp

以上在没有MUI的情况下也可以工作。为组件创建自定义样式的特定于MUI的方法是使用makeStyles()钩子。这将为您提供用作className属性输入的变量,但是当您检查并查看html时,应用的类将具有由MUI生成的名称。

import React from 'react';
import { makeStyles } from '@material-ui/core/styles';
import Button from '@material-ui/core/Button';
const useStyles = makeStyles({
root: {
background: 'linear-gradient(45deg, #FE6B8B 30%, #FF8E53 90%)',
border: 0,
borderRadius: 3,
boxShadow: '0 3px 5px 2px rgba(255, 105, 135, .3)',
color: 'white',
height: 48,
padding: '0 30px',
},
});
export default function MyComponent() {
const classes = useStyles();
return <Button className={classes.root}>Hook</Button>;
}

以上例子摘自https://react.school/material-ui/styling

要了解有关makeStyles()钩子的更多信息,请参阅MUI文档:https://mui.com/system/styles/api/#makestyles-styles-options-hook如果你在同一个页面上滚动,你也可以看到其他与样式相关的钩子的信息。

最新更新