React MUI 属性
React MUI 属性 指的是我们在React组件中用于样式化组件的属性。属性指的是我们提供给组件的高度、宽度、边距、内边距等。在 属性参考表 中可以找到所有可用的 MUI 属性。
现在我们来看一下可以使用的每种类型的属性:
1. System Keys: 包含一个可用于使用 ‘sx’ prop(或作为系统函数)访问此属性的键(或键列表)。
语法:
<Component sx={{ property': 'value' }} />
2. 系统样式函数:
如果你只需要 sx 属性的样式函数的一个子集,你可以仅导入这些函数,而不是完整的包。这对于需要优化最小可能包大小的情况很有用。
语法:
import styled from '@emotion/styled';
import { spacing } from '@mui/system';
const Container1 = styled.div`
${spacing}
`;
3. CSS 属性: 当使用此系统属性时,它指定将创建哪个 CSS 属性。
语法:
.myDiv1 {
margin-top: 10px;
}
4. 主题映射: 最后,这描述了如何将此属性与主题关联起来 – 在本例中,您提供的任何值都将被用作“theme.spacing”辅助输入。
语法:
<Component sx={{ marginTop: theme => theme.spacing(3)}} />
首先,我们将从在VS Code中创建一个React应用程序开始。
步骤1: 通过在任何命令行中编写以下代码来创建React应用程序。
npx create-react-app app_name
步骤2: 然后,我们必须进入我们要工作的文件夹。
cd project_name
步骤3: 我们将安装 @mui/material 库以便在项目中使用。
npm install @mui/material @emotion/react @emotion/styled
项目结构: 在创建React应用程序并安装所有依赖项后,文件夹结构将如下所示:
运行应用程序的步骤:在终端中编写以下代码以运行服务器:
npm start
示例1: 下面是在 React 中使用 System keys 和 System style 函数的代码。
import { Button } from '@mui/material';
import { spacing, palette } from '@mui/system';
import styled from '@emotion/styled';
const Container1 = styled.div`
{spacing}
{palette}
`;
const SystemProperty = () => {
return (
<Container1 bgcolor="yellow" p={2}>
<Button sx={{ width: '200px', m: '10px' }}
variant='contained' color="primary">
Button1
</Button>
<Button sx={{ width: '200px', m: '10px' }}
variant='contained' color="secondary">
Button2
</Button>
</Container1>
);
}
export default SystemProperty;
输出:
示例2: 以下是在React中使用CSS属性和主题映射的代码。
import { Checkbox } from '@mui/material';
import '../index.css';
const CSSTheme = () => {
return (
<div className='container'>
<div className='checkbox'>
Apple
<Checkbox sx={{ marginLeft: theme => theme.spacing(5) }}
defaultChecked variant='contained' color="error">
Checkbox1
</Checkbox>
</div>
<div className='checkbox'>
Orange
<Checkbox sx={{ marginLeft: theme => theme.spacing(4) }}
defaultChecked variant='contained' color="warning">
Checkbox1
</Checkbox>
</div>
<div className='checkbox'>
Guava
<Checkbox sx={{ marginLeft: theme => theme.spacing(5) }}
defaultChecked variant='contained' color="success">
Checkbox1
</Checkbox>
</div>
<div className='checkbox'>
Blueberry
<Checkbox sx={{ marginLeft: theme => theme.spacing(2) }}
defaultChecked variant='contained' color="primary">
Checkbox1
</Checkbox>
</div>
</div>
);
}
export default CSSTheme;
文件名:index.css文件:
.container {
display: flex;
flex-direction: column;
}
.checkbox {
margin: 10px;
}
输出:
参考: https://mui.com/system/properties/