React MUI 调色板
React MUI 调色板 用于调整组件的颜色或指定默认值。 调色板中使用了 Material UI 主题模块。 它可以用于更改组件的颜色以与您的品牌匹配。
默认调色板颜色:
- primary: 用于表示用户的主要界面元素。 它是您应用程序的显示和组件上最频繁出现的颜色。 默认情况下,React MUI 使用主调色板颜色来呈现其组件。
- secondary: 用于作为辅助界面元素。 它为您提供了更多的选项来突出和区分您的产品。 它不是必需的。
- error: 用于表示应明确告知用户的界面方面。
- warning: 用于表示可能存在风险的行为或关键消息。
- info: 用于向用户提供中性和不一定重要的信息。
- success: 用于表示用户触发的操作成功完成。
默认调色板颜色的语法:
<Component color='colorName' />
自定义调色板颜色:
通过在您的主题中提供调色板对象,您可以改变默认的调色板设置。如果提供了任何默认颜色,它将被覆盖。调色板使用React MUI主题模块进行颜色定制。
自定义调色板颜色的语法:
const theme = createTheme({
palette: {
primary: {
main: color,
},
},
});
首先,我们将开始在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:
以下是在Button组件中使用默认调色板颜色的代码。
import { Button } from '@mui/material';
const DefaultPalette = () => {
return (
<div>
<Button
sx={{ width: '200px', margin: '10px' }}
variant='contained' color="primary">Primary</Button>
<Button
sx={{ width: '200px', margin: '10px' }}
variant='contained' color="secondary">Secondary</Button>
<Button
sx={{ width: '200px', margin: '10px' }}
variant='contained' color="error">Error</Button>
<br />
<Button
sx={{ width: '200px', margin: '10px' }}
variant='contained' color="warning">Warning</Button>
<Button
sx={{ width: '200px', margin: '10px' }}
variant='contained' color="info">Info</Button>
<Button
sx={{ width: '200px', margin: '10px' }}
variant='contained' color="success">Success</Button>
</div>
);
}
export default DefaultPalette;
输出:
示例2: 以下是在复选框组件中使用自定义调色板颜色的代码。
import { Checkbox } from '@mui/material';
import { createTheme, ThemeProvider } from '@mui/material/styles';
import { pink, yellow } from '@mui/material/colors';
const theme = createTheme({
palette: {
primary: {
main: pink[500],
},
secondary: {
main: '#2bbccc',
},
success: {
main: '#000000',
},
warning: {
main: yellow[700],
},
info: {
main: '#6b2bcc',
},
error: {
main: '#69cc2b',
},
},
});
const Customized = () => {
return (
<ThemeProvider theme={theme}>
<Checkbox defaultChecked color='primary' />
<Checkbox defaultChecked color="secondary" />
<Checkbox defaultChecked color="success" />
<Checkbox defaultChecked color="error" />
<Checkbox defaultChecked color="info" />
<Checkbox defaultChecked color="warning" />
</ThemeProvider>
);
}
export default Customized;
输出:
参考: https://mui.com/material-ui/customization/palette/