三亩地 三亩地SAN MU DI · CODE DIARY
ARTICLE DETAIL

日记详情

真实记录编程学习的某一天,欢迎挑你感兴趣的翻一翻。

革命性量子编译工具cirdit_multimodal_compile_3to5qubit_v1.1:3-5量子比特电路的终极解决方案

革命性量子编译工具cirdit_multimodal_compile_3to5qubit_v1.1:3-5量子比特电路的终极解决方案

如何定制Mantine UI组件:从样式覆盖到主题扩展的完整指南

【免费下载链接】ui.mantine.devMantine UI website and components项目地址: https://gitcode.com/gh_mirrors/ui/ui.mantine.dev

Mantine UI是一个功能强大的React组件库,提供了丰富的可定制化选项。无论是简单的样式调整还是复杂的主题扩展,Mantine都提供了灵活的解决方案。本文将为您详细介绍如何有效地定制Mantine UI组件,从基础样式覆盖到高级主题配置,帮助您打造独特的用户界面体验。

🔧 Mantine UI组件定制的基本方法

使用style和sx属性快速调整样式

Mantine组件提供了stylesx属性,这是最简单的定制方式。style属性接受标准的CSS-in-JS对象,而sx属性则支持响应式样式和主题变量:

import { Button } from '@mantine/core'; // 使用style属性 <Button style={{ backgroundColor: '#ff6b6b', borderRadius: '8px' }}> 自定义按钮 </Button> // 使用sx属性(支持响应式) <Button sx={(theme) => ({ backgroundColor: theme.colors.blue[6], '&:hover': { backgroundColor: theme.colors.blue[7] }, [theme.fn.smallerThan('sm')]: { fontSize: theme.fontSizes.xs } })}> 响应式按钮 </Button>

通过className属性应用CSS模块

对于更复杂的样式定制,可以使用CSS模块。Mantine组件都支持className属性:

// CustomButton.module.css .customButton { background: linear-gradient(45deg, #ff6b6b, #ffa726); border: 2px solid #ff6b6b; transition: all 0.3s ease; } .customButton:hover { transform: translateY(-2px); box-shadow: 0 4px 12px rgba(255, 107, 107, 0.3); }

🎨 主题定制与扩展

创建自定义主题

Mantine的主题系统非常灵活,您可以在MantineProvider中定义全局主题:

import { MantineProvider } from '@mantine/core'; const theme = { colors: { brand: ['#f0f9ff', '#e0f2fe', '#bae6fd', '#7dd3fc', '#38bdf8', '#0ea5e9', '#0284c7', '#0369a1', '#075985', '#0c4a6e'], }, primaryColor: 'brand', fontFamily: 'Inter, -apple-system, BlinkMacSystemFont, sans-serif', spacing: { xs: 8, sm: 16, md: 24, lg: 32, xl: 40 }, }; function App() { return ( <MantineProvider theme={theme}> <YourApp /> </MantineProvider> ); }

扩展组件默认属性

通过MantineProviderdefaultProps可以全局设置组件的默认属性:

const theme = { components: { Button: { defaultProps: { radius: 'md', size: 'md', variant: 'filled', }, styles: (theme) => ({ root: { fontWeight: 600, }, }), }, Card: { defaultProps: { shadow: 'sm', padding: 'lg', radius: 'md', }, }, }, };

🖼️ 自定义图标与图片组件

使用自定义图标

Mantine支持自定义图标,您可以使用SVG图标或图片资源:

import { Icon } from '@mantine/core'; // 使用SVG图标 const CityIcon = () => ( <svg width="24" height="24" viewBox="0 0 24 24"> {/* SVG路径 */} </svg> ); // 在组件中使用 <Button leftIcon={<CityIcon />}>城市主题</Button> // 使用图片作为图标 <Avatar src="./lib/ImageCheckboxes/icons/city.png" alt="城市图标" />

城市主题图标示例 - 可用于Mantine Avatar组件

山脉图标示例 - 可用于主题切换功能

创建图片选择器组件

基于Mantine的Checkbox组件,您可以创建图片选择器:

import { Checkbox, Group } from '@mantine/core'; const ImageCheckbox = ({ image, label, ...props }) => ( <Checkbox label={ <Group spacing="sm"> <img src={image} alt={label} style={{ width: 32, height: 32, borderRadius: '4px' }} /> <span>{label}</span> </Group> } {...props} /> );

📁 项目结构与组件组织

组件目录结构

在项目中,Mantine组件通常按功能组织:

lib/ ├── ButtonCopy/ # 复制按钮组件 │ ├── ButtonCopy.tsx │ ├── ButtonCopy.story.tsx │ └── ButtonCopy.test.tsx ├── CardGradient/ # 渐变卡片组件 │ ├── CardGradient.tsx │ └── CardGradient.module.css └── AuthenticationForm/ # 认证表单组件 ├── AuthenticationForm.tsx ├── GoogleButton.tsx └── TwitterButton.tsx

创建可复用的定制组件

以创建自定义卡片组件为例:

// lib/CustomCard/CustomCard.tsx import { Card, Text, Group, Badge } from '@mantine/core'; import classes from './CustomCard.module.css'; interface CustomCardProps { title: string; description: string; tags: string[]; image?: string; } export function CustomCard({ title, description, tags, image }: CustomCardProps) { return ( <Card shadow="md" padding="lg" radius="md" className={classes.card} > {image && ( <Card.Section> <img src={image} alt={title} className={classes.image} /> </Card.Section> )} <Text fw={500} size="lg" mt="md"> {title} </Text> <Text c="dimmed" size="sm" mt="xs"> {description} </Text> <Group gap="xs" mt="md"> {tags.map((tag) => ( <Badge key={tag} variant="light" color="blue"> {tag} </Badge> ))} </Group> </Card> ); }

🎯 高级定制技巧

使用CSS变量进行动态主题

Mantine支持CSS变量,这使得动态主题切换变得简单:

// 在主题中定义CSS变量 const theme = { globalStyles: (theme) => ({ ':root': { '--mantine-color-primary': theme.colors.blue[6], '--mantine-color-secondary': theme.colors.grape[6], '--mantine-border-radius': theme.radius.md, }, }), }; // 在组件中使用CSS变量 const CustomComponent = styled('div')` background-color: var(--mantine-color-primary); border-radius: var(--mantine-border-radius); padding: var(--mantine-spacing-md); `;

创建复合组件

将多个Mantine组件组合成更复杂的复合组件:

// lib/FormSection/FormSection.tsx import { Paper, Title, Text, Stack } from '@mantine/core'; interface FormSectionProps { title: string; description?: string; children: React.ReactNode; } export function FormSection({ title, description, children }: FormSectionProps) { return ( <Paper shadow="xs" p="md" withBorder> <Stack gap="md"> <div> <Title order={3}>{title}</Title> {description && ( <Text c="dimmed" size="sm"> {description} </Text> )} </div> {children} </Stack> </Paper> ); }

🔄 响应式设计与断点定制

自定义断点

Mantine允许您自定义响应式断点:

const theme = { breakpoints: { xs: '360px', sm: '640px', md: '768px', lg: '1024px', xl: '1280px', }, spacing: { xs: '0.5rem', sm: '0.75rem', md: '1rem', lg: '1.5rem', xl: '2rem', }, };

响应式样式示例

<Box sx={(theme) => ({ padding: theme.spacing.md, // 移动端样式 [theme.fn.smallerThan('sm')]: { padding: theme.spacing.xs, fontSize: theme.fontSizes.sm, }, // 平板端样式 [theme.fn.largerThan('md')]: { padding: theme.spacing.lg, maxWidth: '1200px', margin: '0 auto', }, })} > 响应式内容 </Box>

🧪 测试与文档

编写组件故事

使用Storybook为定制组件创建文档:

// CustomButton.story.tsx import type { Meta, StoryObj } from '@storybook/react'; import { CustomButton } from './CustomButton'; const meta: Meta<typeof CustomButton> = { title: 'Components/CustomButton', component: CustomButton, tags: ['autodocs'], }; export default meta; type Story = StoryObj<typeof CustomButton>; export const Primary: Story = { args: { children: '主要按钮', variant: 'filled', color: 'blue', }, }; export const WithIcon: Story = { args: { children: '带图标按钮', leftIcon: <IconHome />, }, };

单元测试示例

// CustomButton.test.tsx import { render, screen, fireEvent } from '@testing-library/react'; import { CustomButton } from './CustomButton'; describe('CustomButton', () => { it('渲染正确的文本', () => { render(<CustomButton>点击我</CustomButton>); expect(screen.getByText('点击我')).toBeInTheDocument(); }); it('点击时触发onClick事件', () => { const handleClick = jest.fn(); render(<CustomButton onClick={handleClick}>测试按钮</CustomButton>); fireEvent.click(screen.getByText('测试按钮')); expect(handleClick).toHaveBeenCalledTimes(1); }); });

💡 最佳实践与建议

  1. 保持一致性:在整个应用中使用统一的主题变量和设计令牌
  2. 渐进增强:从基础组件开始,逐步添加定制功能
  3. 性能优化:避免在渲染函数中创建样式对象
  4. 可访问性:确保定制组件符合WCAG标准
  5. 文档化:为自定义组件编写清晰的文档和使用示例

海洋主题图标示例 - 可用于天气或旅游相关应用

冬季主题图标示例 - 适合季节性主题定制

通过掌握这些Mantine UI定制技巧,您可以创建既美观又功能强大的用户界面。记住,好的定制应该增强用户体验,而不是增加复杂性。从简单的样式调整开始,逐步探索更高级的主题定制功能,您将能够打造出真正独特的应用程序界面。

Mantine的强大之处在于它的灵活性和一致性 - 您可以在保持设计系统完整性的同时,实现完全个性化的外观和感觉。开始定制您的第一个Mantine组件吧!

【免费下载链接】ui.mantine.devMantine UI website and components项目地址: https://gitcode.com/gh_mirrors/ui/ui.mantine.dev

创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考

← 返回列表