React MUI全局样式API
React MUI是一个UI库,它提供了功能全面的组件,将我们自己的设计系统引入到我们准备好的组件中。MUI是一个用户界面库,它为快速和简单的Web开发提供了预定义和可定制的React组件,这些Material-UI组件是基于谷歌的Material Design设计的。
在本文中,我们将讨论React MUI GlobalStyles API。GlobalStyles用于为某些HTML元素添加全局基线样式。如果您正在使用CssBaseline组件添加基线样式,GlobalStyles还将这些全局样式作为对该组件的覆盖添加。
导入GlobalStyles API:
import GlobalStyles from '@mui/material/GlobalStyles';
// or
import { GlobalStyles } from '@mui/material';
属性列表:
- styles: 允许我们添加全局应用的样式。其类型包括,func | number | object | { __emotion_styles: any } | string | bool。
创建React项目:
步骤1: 创建一个React应用,通过npm命令安装React模块。
npm create-react-app project name
步骤2: 创建完你的React项目后,进入文件夹执行不同的操作。
cd project name
步骤3: 创建ReactJS应用后,使用以下命令安装所需模块:
npm install @mui/material @emotion/react @emotion/styled
项目结构:
运行应用程序的步骤: 打开终端并输入以下命令。
npm start
示例1:
下面的示例演示了React MUI的GlobalStyles API。
import React from "react";
import GlobalStyles from "@mui/material/GlobalStyles";
function App() {
return (
<center>
<div>
<h1 style={{ color: "green" }}>GeeksforGeeks</h1>
<h2>React MUI GlobalStyles API</h2>
</div>
<div style={{ width: "50%" }}>
<GlobalStyles styles={{ h1: { color: 'green' } }} />
<h1>Welcome to GeeksforGeeks</h1>
</div>
</center>
);
}
export default App;
输出:
示例2: 下面的示例演示了React MUI GlobalStyles API。
import React from "react";
import GlobalStyles from "@mui/material/GlobalStyles";
function App() {
return (
<center>
<div>
<h1 style={{ color: "green" }}>GeeksforGeeks</h1>
<h2>React MUI GlobalStyles API</h2>
</div>
<div style={{ width: "50%" }}>
<GlobalStyles
styles={{
h1: { color: "green" },
p: { color: "gray" },
button: { backgroundColor: "green", padding: 20 },
a: { textDecoration: "none", color: "white" },
}}
/>
<h1>Welcome to GeeksforGeeks</h1>
<p>
Find articles related to programming,
data structures, algorithms,
etc.
</p>
<button>
<a href="geeksforgeeks.org">Visit</a>
</button>
</div>
</center>
);
}
export default App;
输出:
参考: https://mui.com/material-ui/api/global-styles/