xmirror-components
v1.0.39
Published
一个基于 React + TypeScript + Ant Design 的现代化组件库,提供高质量、可复用的 UI 组件和 Hooks。
Readme
XMirror Components
一个基于 React + TypeScript + Ant Design 的现代化组件库,提供高质量、可复用的 UI 组件和 Hooks。
🚀 特性
- TypeScript 支持: 完整的类型定义和类型安全
- 现代化架构: 基于 React 18+ 和最新的前端技术栈
- Ant Design 集成: 与 Ant Design 5.x 完美集成
- 高性能: 优化的渲染性能和内存管理
- 可扩展: 模块化设计,易于扩展和定制
- 国际化: 内置多语言支持
📦 安装
npm install xmirror-components🔧 依赖要求
{
"peerDependencies": {
"antd": ">=5.0.0",
"react": ">=18.0.0",
"react-dom": ">=18.0.0",
"@ant-design/icons": ">=5.0.0",
"ahooks": ">=3.0.0",
"lodash-es": ">=4.17.0",
"react-intl": ">=7.0.0",
"react-transition-group": ">=4.4.0"
}
}🎯 核心组件
AntdApp
Ant Design 应用的根组件,提供全局配置和主题支持。集成了全局加载状态管理和配置提供者功能。
特性
- 全局状态管理: 集成 message、notification、modal 等全局方法
- 配置支持: 内置 ConfigProvider 配置支持
- 加载状态: 集成 GlobalLoading 全局加载状态
- 类型安全: 完整的 TypeScript 类型支持
基本用法
import { App, message, notification, modal } from 'xmirror-components'
function MyApp() {
return (
<App
config={{
iconButton: {
size: 'small',
style: { color: '#1890ff' }
},
iconFont: {
className: 'my-iconfont'
}
}}
>
<div>你的应用内容</div>
</App>
)
}
// 使用全局方法
const handleClick = () => {
message.success('操作成功')
notification.info({
message: '通知',
description: '这是一个通知消息'
})
modal.confirm({
title: '确认',
content: '确定要执行此操作吗?',
onOk: () => console.log('确认')
})
}API 参考
| 属性 | 类型 | 默认值 | 说明 |
|------|------|--------|------|
| config | ConfigProviderConfigProps | - | 全局配置选项 |
| children | React.ReactNode | - | 子组件 |
ConfigProvider
配置提供者,用于设置国际化、主题等全局配置。支持组件级别的配置覆盖。
特性
- 递归合并: 支持配置的深度合并
- 类型安全: 完整的 TypeScript 类型定义
- 组件配置: 支持 IconButton、IconFont 等组件的全局配置
基本用法
import { ConfigProvider } from 'xmirror-components'
function App() {
return (
<ConfigProvider
config={{
iconButton: {
size: 'middle',
style: {
color: '#1890ff',
borderRadius: '4px'
},
className: 'custom-icon-button'
},
iconFont: {
className: 'my-iconfont',
style: { fontSize: '16px' }
}
}}
>
<div>你的应用内容</div>
</ConfigProvider>
)
}API 参考
| 属性 | 类型 | 默认值 | 说明 |
|------|------|--------|------|
| config | ConfigProviderConfigProps | - | 配置对象 |
ConfigProviderConfigProps
interface ConfigProviderConfigProps {
iconButton?: {
size?: 'small' | 'middle' | 'large'
style?: React.CSSProperties
className?: string
render?: (props: any) => React.ReactNode
}
iconFont?: {
className?: string
style?: React.CSSProperties
}
}Table
功能强大的表格组件,支持排序、筛选、分页、列设置、列宽调整等功能。
特性
- 列管理: 支持列的显示/隐藏、排序、宽度调整
- 本地存储: 自动保存用户的列配置到本地存储
- 响应式: 支持响应式布局和滚动
- 可扩展: 支持自定义渲染和样式
- 类型安全: 完整的 TypeScript 泛型支持
基本用法
import { Table } from 'xmirror-components'
function UserTable() {
const columns = [
{
title: '姓名',
dataIndex: 'name',
key: 'name',
sorter: true,
filters: [
{ text: '张三', value: 'zhangsan' },
{ text: '李四', value: 'lisi' }
]
},
{
title: '年龄',
dataIndex: 'age',
key: 'age',
sorter: true
},
{
title: '邮箱',
dataIndex: 'email',
key: 'email',
ellipsis: true
}
]
const dataSource = [
{ id: 1, name: '张三', age: 25, email: '[email protected]' },
{ id: 2, name: '李四', age: 30, email: '[email protected]' }
]
return (
<Table
columns={columns}
dataSource={dataSource}
rowKey="id"
pagination={{
current: 1,
pageSize: 10,
total: 100
}}
columnsSort={true}
columnsVisible={true}
columnsResizable={true}
tableId="user-table"
/>
)
}高级用法
// 自定义列渲染
const columns = [
{
title: '状态',
dataIndex: 'status',
key: 'status',
render: (status: string) => (
<Tag color={status === 'active' ? 'green' : 'red'}>
{status === 'active' ? '激活' : '禁用'}
</Tag>
)
},
{
title: '操作',
key: 'action',
render: (_, record) => (
<Space>
<IconButton icon="edit" onClick={() => handleEdit(record)} />
<IconButton icon="delete" onClick={() => handleDelete(record)} />
</Space>
)
}
]
// 使用本地存储的列配置
<Table
columns={columns}
dataSource={dataSource}
columnsSort={true} // 启用列排序
columnsVisible={true} // 启用列显示/隐藏
columnsResizable={true} // 启用列宽调整
tableId="unique-table-id" // 唯一标识,用于本地存储
/>API 参考
| 属性 | 类型 | 默认值 | 说明 |
|------|------|--------|------|
| columns | ColumnType[] | [] | 表格列配置 |
| dataSource | any[] | [] | 数据源 |
| columnsSort | boolean | false | 是否启用列排序 |
| columnsVisible | boolean | false | 是否启用列显示/隐藏 |
| columnsResizable | boolean | false | 是否启用列宽调整 |
| tableId | string | '' | 表格唯一标识,用于本地存储 |
SearchArea
搜索区域组件,提供灵活的搜索和筛选功能。支持展开/收起动画和自定义布局。
特性
- 动画效果: 平滑的展开/收起动画
- 响应式布局: 支持多种屏幕尺寸的响应式布局
- 自定义配置: 支持自定义列布局和样式
- Hook支持: 提供 useSearchArea Hook 进行状态管理
基本用法
import { SearchArea } from 'xmirror-components'
function SearchForm() {
const handleSearch = (values: any) => {
console.log('搜索参数:', values)
}
const handleReset = () => {
console.log('重置搜索')
}
return (
<SearchArea
onSearch={handleSearch}
onReset={handleReset}
loading={false}
>
<SearchArea.Item name="name" label="姓名">
<Input placeholder="请输入姓名" />
</SearchArea.Item>
<SearchArea.Item name="status" label="状态">
<Select placeholder="请选择状态">
<Option value="active">激活</Option>
<Option value="inactive">禁用</Option>
</Select>
</SearchArea.Item>
</SearchArea>
)
}使用 Hook 管理状态
import { SearchArea } from 'xmirror-components'
function AdvancedSearch() {
const searchArea = SearchArea.useSearchArea(false) // 默认收起
return (
<div>
<SearchArea.ToggleButton
onClick={searchArea.toggle}
show={searchArea.show}
>
高级搜索
</SearchArea.ToggleButton>
<SearchArea
instance={searchArea}
onSearch={handleSearch}
>
{/* 搜索表单项 */}
</SearchArea>
</div>
)
}API 参考
| 属性 | 类型 | 默认值 | 说明 |
|------|------|--------|------|
| onSearch | (data: any) => void | - | 搜索回调函数 |
| onReset | () => void | - | 重置回调函数 |
| onClose | () => void | - | 收起回调函数 |
| loading | boolean | false | 加载状态 |
| instance | SearchAreaHooks | - | 外部状态管理实例 |
| col | ColProps | {} | 列配置 |
| row | RowProps | {} | 行配置 |
GlobalLoading
全局加载状态管理组件,提供美观的加载动画和全局状态控制。
特性
- 动画效果: 流畅的进入/退出动画
- 全局控制: 通过 setGlobalLoading 函数全局控制
- 美观设计: 现代化的加载动画效果
- 高性能: 使用 CSSTransition 优化性能
基本用法
import { GlobalLoading, setGlobalLoading } from 'xmirror-components'
function App() {
const handleAsyncOperation = async () => {
setGlobalLoading(true)
try {
await fetchData()
} finally {
setGlobalLoading(false)
}
}
return (
<div>
<button onClick={handleAsyncOperation}>
执行异步操作
</button>
<GlobalLoading />
</div>
)
}在 AntdApp 中使用
import { App, setGlobalLoading } from 'xmirror-components'
// AntdApp 已内置 GlobalLoading,可直接使用
function MyApp() {
const handleRequest = async () => {
setGlobalLoading(true)
try {
await api.getData()
} finally {
setGlobalLoading(false)
}
}
return <App>{/* 你的应用 */}</App>
}API 参考
| 方法 | 类型 | 说明 |
|------|------|------|
| setGlobalLoading | (loading: boolean) => void | 设置全局加载状态 |
IconButton
图标按钮组件,支持多种图标类型和自定义配置。
特性
- 图标支持: 支持 IconFont 和 React 图标组件
- Tooltip 支持: 内置 Tooltip 提示功能
- 权限控制: 支持权限标识和隐藏控制
- 样式定制: 支持自定义样式和主题
基本用法
import { IconButton } from 'xmirror-components'
function ActionButtons() {
return (
<Space>
<IconButton
icon="edit"
title="编辑"
onClick={() => console.log('编辑')}
/>
<IconButton
icon="delete"
title="删除"
disabled
disabledReason="无权限删除"
onClick={() => console.log('删除')}
/>
<IconButton
icon={<CustomIcon />}
title="自定义图标"
size="large"
loading
/>
</Space>
)
}使用 React 图标
import { EditOutlined, DeleteOutlined } from '@ant-design/icons'
function CustomButtons() {
return (
<Space>
<IconButton
icon={<EditOutlined />}
title="编辑"
onClick={handleEdit}
/>
<IconButton
icon={<DeleteOutlined />}
title="删除"
onClick={handleDelete}
/>
</Space>
)
}API 参考
| 属性 | 类型 | 默认值 | 说明 |
|------|------|--------|------|
| icon | React.ReactNode \| string | - | 图标 |
| title | React.ReactNode | - | 提示内容 |
| onClick | (e: React.MouseEvent) => void | - | 点击事件 |
| disabled | boolean | false | 是否禁用 |
| disabledReason | React.ReactNode | - | 禁用原因 |
| hide | boolean | false | 是否隐藏 |
| size | 'small' \| 'middle' \| 'large' | 'small' | 按钮大小 |
| loading | boolean | false | 加载状态 |
IconFont
图标字体组件,支持自定义图标字体。
特性
- 字体图标: 支持 iconfont 字体图标
- Symbol 模式: 支持 SVG Symbol 模式
- 样式定制: 支持自定义样式和类名
- 类型安全: 完整的 TypeScript 类型支持
基本用法
import { IconFont } from 'xmirror-components'
function IconExamples() {
return (
<Space>
{/* 字体图标模式 */}
<IconFont type="icon-home" />
<IconFont type="icon-user" size={24} />
{/* Symbol 模式 */}
<IconFont type="icon-setting" symbol />
</Space>
)
}配置全局样式
import { ConfigProvider } from 'xmirror-components'
function App() {
return (
<ConfigProvider
config={{
iconFont: {
className: 'my-iconfont',
style: { fontSize: '16px', color: '#1890ff' }
}
}}
>
<IconFont type="icon-custom" />
</ConfigProvider>
)
}API 参考
| 属性 | 类型 | 默认值 | 说明 |
|------|------|--------|------|
| type | string | - | 图标类型 |
| symbol | boolean | false | 是否使用 Symbol 模式 |
| className | string | - | 自定义类名 |
| style | React.CSSProperties | - | 自定义样式 |
SwitchValue
开关值组件,支持自定义选中和未选中的值。
特性
- 自定义值: 支持任意类型的选中/未选中值
- 类型安全: 完整的 TypeScript 泛型支持
- 简单易用: 与原生 Switch 组件 API 一致
基本用法
import { SwitchValue } from 'xmirror-components'
function SwitchExamples() {
const [status, setStatus] = useState('active')
return (
<Space direction="vertical">
{/* 字符串值 */}
<SwitchValue
checked={status}
trueValue="active"
falseValue="inactive"
onChange={(value) => setStatus(value)}
/>
{/* 数字值 */}
<SwitchValue
checked={isEnabled}
trueValue={1}
falseValue={0}
onChange={(value) => setIsEnabled(value)}
/>
{/* 对象值 */}
<SwitchValue
checked={config}
trueValue={{ enabled: true, level: 'high' }}
falseValue={{ enabled: false, level: 'low' }}
onChange={(value) => setConfig(value)}
/>
</Space>
)
}API 参考
| 属性 | 类型 | 默认值 | 说明 |
|------|------|--------|------|
| checked | T \| F | - | 当前值 |
| trueValue | T | true | 选中值 |
| falseValue | F | false | 未选中值 |
| onChange | (value: T \| F, event) => void | - | 值变化回调 |
CheckboxValue
复选框值组件,支持自定义选中值和标签。
特性
- 自定义值: 支持任意类型的选中/未选中值
- 自定义标签: 支持自定义显示标签
- 类型安全: 完整的 TypeScript 泛型支持
基本用法
import { CheckboxValue } from 'xmirror-components'
function CheckboxExamples() {
const [agreed, setAgreed] = useState(false)
return (
<Space direction="vertical">
{/* 基本用法 */}
<CheckboxValue
checked={agreed}
trueValue={true}
falseValue={false}
trueLabel="同意协议"
falseLabel="不同意协议"
onChange={(value) => setAgreed(value)}
/>
{/* 自定义值 */}
<CheckboxValue
checked={permission}
trueValue="admin"
falseValue="user"
trueLabel="管理员权限"
falseLabel="普通用户权限"
onChange={(value) => setPermission(value)}
/>
</Space>
)
}API 参考
| 属性 | 类型 | 默认值 | 说明 |
|------|------|--------|------|
| checked | T \| F | - | 当前值 |
| trueValue | T | true | 选中值 |
| falseValue | F | false | 未选中值 |
| trueLabel | string | '' | 选中标签 |
| falseLabel | string | '' | 未选中标签 |
| onChange | (value: T \| F, event) => void | - | 值变化回调 |
🪝 核心 Hooks
useTable
一个功能强大的表格数据管理 Hook,提供完整的数据获取、分页、排序、筛选、多选等功能。
特性
- 类型安全: 完整的 TypeScript 泛型支持
- 数据管理: 自动处理数据获取、缓存和更新
- 分页支持: 内置分页逻辑和状态管理
- 排序筛选: 支持列排序和条件筛选
- 多选支持: 支持行选择和跨页选择
- 定时刷新: 可配置的定时数据刷新
- 错误处理: 完善的错误处理和用户提示
- 性能优化: 使用 useMemoizedFn 和 useCallback 优化性能
基本用法
import { useTable } from 'xmirror-components/hooks/useTable'
interface User {
id: number
name: string
email: string
status: 'active' | 'inactive'
}
function UserTable() {
const { tableProps, search, rowSelection } = useTable<User>(
// 请求函数
async (params) => {
const response = await fetchUsers(params)
return {
records: response.data,
total: response.total,
current: response.current,
size: response.pageSize
}
},
// 配置选项
{
rowKey: 'id',
immediate: true,
showRowSelection: true,
defaultPagination: {
current: 1,
pageSize: 20
}
}
)
return (
<Table
{...tableProps}
columns={[
{ title: 'ID', dataIndex: 'id', key: 'id' },
{ title: '姓名', dataIndex: 'name', key: 'name' },
{ title: '邮箱', dataIndex: 'email', key: 'email' },
{ title: '状态', dataIndex: 'status', key: 'status' }
]}
/>
)
}高级用法
const { tableProps, search, rowSelection } = useTable<User>(
fetchUsers,
{
rowKey: 'id',
interval: 30000, // 30秒自动刷新
multiPageSelection: true, // 支持跨页选择
onBeforeRequest: async (params) => {
// 请求前处理
console.log('请求参数:', params)
return params
},
onAfterRequest: async (response) => {
// 响应后处理
console.log('响应数据:', response)
return response.records
}
}
)API 参考
OptionsProps
| 属性 | 类型 | 默认值 | 说明 |
|------|------|--------|------|
| rowKey | keyof T \| string | 'id' | 行数据的唯一标识字段 |
| interval | false \| number | false | 定时刷新间隔(毫秒) |
| immediate | boolean | true | 是否立即执行首次请求 |
| defaultPagination | object | {current: 1, pageSize: 10} | 默认分页配置 |
| showRowSelection | boolean | false | 是否显示行选择 |
| multiPageSelection | boolean | false | 是否支持跨页选择 |
| onBeforeRequest | function | - | 请求前回调函数 |
| onAfterRequest | function | - | 响应后回调函数 |
ReturnData
| 属性 | 类型 | 说明 |
|------|------|------|
| loading | boolean | 加载状态 |
| tableProps | object | 表格组件的 props |
| search | object | 搜索相关功能 |
| rowSelection | object | 行选择相关功能 |
搜索和筛选
// 提交搜索
search.submit({ status: 'active', keyword: 'john' })
// 刷新数据
search.refresh()
// 获取当前搜索参数
console.log(search.params)
// 获取分页信息
console.log(search.pagination)行选择
// 获取选中的行
console.log(rowSelection.selectedRows)
// 获取选中的行键
console.log(rowSelection.selectedRowKeys)useRequest
基于 ahooks 的请求管理 Hook,提供请求状态管理和缓存功能。扩展了错误处理和数据处理能力。
特性
- 错误处理: 自动显示错误消息,支持自定义错误处理
- 数据处理: 自动处理嵌套的响应数据结构
- 类型安全: 完整的 TypeScript 泛型支持
- 缓存支持: 基于 ahooks 的缓存机制
- 插件系统: 支持 ahooks 插件生态
基本用法
import { useEffect } from 'react'
import { Select } from 'antd'
import { useRequest } from 'xmirror-components'
import { getUserOptions } from '@/api/home/user'
function Index ({ ...props }) {
const {
loading,
data
} = useRequest(getUserOptions)
return (
<Select
className="w-180"
loading={loading}
placeholder="请选择"
options={data}
{...props}
/>
)
}
export default Indeximport { useEffect } from 'react'
import { Select } from 'antd'
import { useRequest } from 'xmirror-components'
import { getProfitOptions } from '@/api/home/vendor/credit/detail/listing-information'
interface Props {
vendorId: string
[prop: string]: any
}
function Index ({ vendorId, ...props }: Props) {
const {
loading,
data,
run
} = useRequest(() => {
return getProfitOptions(vendorId)
}, {
manual: true // 关闭自动进入页面自动请求
})
useEffect(() => {
if (vendorId) {
run()
}
}, [vendorId])
return (
<Select
className="w-180"
loading={loading}
placeholder="请选择季度"
options={data}
{...props}
/>
)
}
export default Index处理嵌套数据结构
// 当 API 返回 { code: 200, data: [...], success: true } 格式时
const { data } = useRequest(
async () => {
const response = await fetch('/api/users')
return response.json() // 返回 { code: 200, data: [...], success: true }
}
)
// data 将直接是用户数组,而不是 { code, data, success } 对象
console.log(data) // [...]自定义错误处理
const { data, loading } = useRequest(
fetchUsers,
{
errorMessage: false, // 禁用自动错误消息
onError: (error) => {
// 自定义错误处理
console.error('请求失败:', error)
notification.error({
message: '自定义错误提示',
description: error.message
})
}
}
)使用插件
import { useRequest } from 'xmirror-components'
import { useDebouncePlugin, usePollingPlugin } from 'ahooks'
function SearchComponent() {
const [keyword, setKeyword] = useState('')
const { data, loading } = useRequest(
(params) => searchUsers(params),
{
errorMessage: true,
refreshDeps: [keyword]
},
[
useDebouncePlugin({ wait: 300 }), // 防抖
usePollingPlugin({ interval: 5000 }) // 轮询
]
)
return (
<div>
<Input
value={keyword}
onChange={(e) => setKeyword(e.target.value)}
placeholder="搜索用户"
/>
{/* 搜索结果 */}
</div>
)
}API 参考
| 属性 | 类型 | 默认值 | 说明 |
|------|------|--------|------|
| errorMessage | boolean | true | 是否显示错误消息 |
| onError | (error: Error, params: any[]) => void | - | 错误回调函数 |
返回值
| 属性 | 类型 | 说明 |
|------|------|------|
| data | TData | 处理后的数据 |
| loading | boolean | 加载状态 |
| error | Error \| undefined | 错误信息 |
| refresh | () => void | 刷新函数 |
| mutate | (data: TData) => void | 手动设置数据 |
| cancel | () => void | 取消请求 |
扩展选项
useRequest 支持所有 ahooks useRequest 的选项,包括:
cacheKey: 缓存键refreshDeps: 依赖刷新pollingInterval: 轮询间隔ready: 是否准备就绪onSuccess: 成功回调onError: 错误回调onFinally: 完成回调
🚀 快速开始
完整示例
import React from 'react'
import {
App,
Table,
SearchArea,
IconButton,
useTable,
useRequest,
message
} from 'xmirror-components'
import { Input, Select, Button, Space } from 'antd'
// 用户管理页面示例
function UserManagement() {
// 使用 useTable Hook 管理表格数据
const { tableProps, search, rowSelection } = useTable(
async (params) => {
const response = await fetch('/api/users', {
method: 'POST',
body: JSON.stringify(params)
})
return response.json()
},
{
rowKey: 'id',
showRowSelection: true,
defaultPagination: { current: 1, pageSize: 20 }
}
)
// 使用 useRequest Hook 处理删除操作
const { run: deleteUser } = useRequest(
async (id: number) => {
await fetch(`/api/users/${id}`, { method: 'DELETE' })
},
{
onSuccess: () => {
message.success('删除成功')
search.refresh() // 刷新表格
}
}
)
const columns = [
{
title: '姓名',
dataIndex: 'name',
key: 'name',
sorter: true
},
{
title: '邮箱',
dataIndex: 'email',
key: 'email'
},
{
title: '状态',
dataIndex: 'status',
key: 'status',
render: (status: string) => (
<span style={{ color: status === 'active' ? 'green' : 'red' }}>
{status === 'active' ? '激活' : '禁用'}
</span>
)
},
{
title: '操作',
key: 'action',
render: (_, record) => (
<Space>
<IconButton
icon="edit"
title="编辑"
onClick={() => handleEdit(record)}
/>
<IconButton
icon="delete"
title="删除"
onClick={() => deleteUser(record.id)}
/>
</Space>
)
}
]
return (
<div>
{/* 搜索区域 */}
<SearchArea
onSearch={(values) => search.submit(values)}
onReset={() => search.submit({})}
>
<SearchArea.Item name="name" label="姓名">
<Input placeholder="请输入姓名" />
</SearchArea.Item>
<SearchArea.Item name="status" label="状态">
<Select placeholder="请选择状态">
<Select.Option value="active">激活</Select.Option>
<Select.Option value="inactive">禁用</Select.Option>
</Select>
</SearchArea.Item>
</SearchArea>
{/* 表格 */}
<Table
{...tableProps}
columns={columns}
columnsSort={true}
columnsVisible={true}
columnsResizable={true}
tableId="user-management"
/>
</div>
)
}
// 应用入口
function App() {
return (
<App
config={{
iconButton: {
size: 'small',
style: { color: '#1890ff' }
}
}}
>
<UserManagement />
</App>
)
}
export default App🎨 样式系统
组件库使用 CSS-in-JS 方案,支持主题定制和样式覆盖。
主题定制
import { ConfigProvider } from 'xmirror-components'
function App() {
return (
<ConfigProvider
config={{
iconButton: {
style: {
color: '#1890ff',
borderRadius: '6px'
}
},
iconFont: {
style: {
fontSize: '16px',
color: '#666'
}
}
}}
>
{/* 你的应用 */}
</ConfigProvider>
)
}自定义样式
import styled from '@emotion/styled'
import { Table } from 'xmirror-components'
const CustomTable = styled(Table)`
.ant-table-thead > tr > th {
background-color: #f5f5f5;
font-weight: 600;
}
.ant-table-tbody > tr:hover > td {
background-color: #f0f9ff;
}
`
function MyTable() {
return <CustomTable {...props} />
}🌍 国际化
内置国际化支持,使用 react-intl 实现多语言切换。
基本配置
import { ConfigProvider } from 'xmirror-components'
import { IntlProvider } from 'react-intl'
import zhCN from 'antd/locale/zh_CN'
import enUS from 'antd/locale/en_US'
const messages = {
'zh-CN': require('./locales/zh-CN.json'),
'en-US': require('./locales/en-US.json')
}
function App() {
const [locale, setLocale] = useState('zh-CN')
return (
<IntlProvider locale={locale} messages={messages[locale]}>
<ConfigProvider locale={locale === 'zh-CN' ? zhCN : enUS}>
{/* 你的应用 */}
</ConfigProvider>
</IntlProvider>
)
}📋 最佳实践
1. 组件组合使用
// 推荐:组合使用多个组件
function DataTable() {
const { tableProps, search } = useTable(fetchData)
return (
<div>
<SearchArea onSearch={search.submit}>
{/* 搜索表单项 */}
</SearchArea>
<Table {...tableProps} />
</div>
)
}2. 错误处理
// 推荐:统一的错误处理
const { data, loading, error } = useRequest(fetchData, {
errorMessage: true, // 自动显示错误消息
onError: (error) => {
// 记录错误日志
console.error('API Error:', error)
}
})3. 性能优化
// 推荐:使用 useMemo 优化渲染
const columns = useMemo(() => [
{
title: '姓名',
dataIndex: 'name',
render: (text) => <span>{text}</span>
}
], [])
// 推荐:使用 useCallback 优化事件处理
const handleEdit = useCallback((record) => {
// 编辑逻辑
}, [])4. 类型安全
// 推荐:定义完整的类型
interface User {
id: number
name: string
email: string
status: 'active' | 'inactive'
}
const { tableProps } = useTable<User>(fetchUsers, {
rowKey: 'id'
})🔧 常见问题
Q: 如何自定义表格样式?
A: 使用 styled-components 或 emotion 包装 Table 组件:
import styled from '@emotion/styled'
import { Table } from 'xmirror-components'
const CustomTable = styled(Table)`
.ant-table-thead > tr > th {
background-color: #f5f5f5;
}
`Q: 如何处理大量数据?
A: 使用虚拟滚动或分页加载:
const { tableProps } = useTable(fetchData, {
defaultPagination: { current: 1, pageSize: 50 }
})Q: 如何实现权限控制?
A: 使用 IconButton 的权限属性:
<IconButton
icon="delete"
hide={!hasPermission('delete')}
disabled={!hasPermission('delete')}
disabledReason="无删除权限"
/>📚 开发指南
项目结构
src/
├── components/ # 组件目录
│ ├── AntdApp/ # 应用根组件
│ ├── ConfigProvider/ # 配置提供者
│ ├── Table/ # 表格组件
│ ├── SearchArea/ # 搜索区域
│ └── ... # 其他组件
├── hooks/ # Hooks 目录
│ ├── useTable/ # 表格数据管理 Hook
│ └── useRequest/ # 请求管理 Hook
└── index.ts # 主入口文件开发环境
# 安装依赖
npm install
# 启动开发服务器
npm run dev
# 构建项目
npm run build
# 代码检查
npm run lint添加新组件
- 在
src/components/目录下创建组件目录 - 实现组件逻辑和类型定义
- 在
src/index.ts中导出组件 - 更新文档和示例
添加新 Hook
- 在
src/hooks/目录下创建 Hook 目录 - 实现 Hook 逻辑和类型定义
- 在
src/index.ts中导出 Hook - 更新文档和示例
🤝 贡献指南
我们欢迎所有形式的贡献!请查看 CONTRIBUTING.md 了解详情。
📄 许可证
本项目采用 MIT 许可证 - 查看 LICENSE 文件了解详情。
🔧 最近更新
v1.0.30-alpha.10 (2024-01-XX)
修复
- TypeScript 导入路径修复: 修复了所有文件中的 TypeScript 导入路径问题
- 移除了
src/locale/index.ts中的.ts扩展名 - 移除了
src/components/Table/Footer/index.tsx中的.ts扩展名 - 移除了
src/locale/types.ts中的.ts扩展名 - 移除了
src/main.tsx中的.tsx扩展名 - 修复了 React 导入问题,确保 JSX 正常工作
- 移除了
改进
- 解决了 TypeScript 编译错误,确保项目能够正常构建
- 提升了代码的兼容性和可维护性
- 统一了项目的导入规范
v1.0.30-alpha.8 (2024-01-XX)
新增功能
- 完整文档: 为所有组件和 Hook 编写了详细的使用文档和 API 参考
- 最佳实践: 添加了组件组合使用、错误处理、性能优化等最佳实践指南
- 完整示例: 提供了完整的用户管理页面示例,展示组件库的实际应用
样式系统优化
- ResizableColumns 样式转换: 将
index.less文件转换为@emotion/styled形式- 创建了
styles.ts文件,使用@emotion/styled实现样式组件 - 添加了
react-resizable和@types/react-resizable依赖 - 创建了
utils.ts工具文件,提供dataIndexToString函数 - 修复了所有 TypeScript 类型错误,提升了类型安全性
- 删除了不再需要的
index.less文件
- 创建了
改进
- 统一了项目的样式系统,全部使用
@emotion/styled - 提升了代码的类型安全性和可维护性
- 优化了组件库的构建和打包流程
- 完善了组件库的文档体系,提供更好的开发体验
v1.0.1 (2024-01-XX)
修复
- useTable Hook 类型兼容性修复: 修复了
onChangeTable函数与 Antd Table 组件onChange回调的类型不匹配问题- 更新了
TableChangeParams类型,使current和pageSize属性可选 - 更新了
FilterParams和SortParams类型,提高与 Antd 类型的兼容性 - 优化了排序参数处理逻辑,支持数组形式的排序信息
- 修复了行选择回调函数的类型定义
- 更新了
改进
- 提升了类型安全性,减少了 TypeScript 编译错误
- 优化了代码的可维护性和扩展性
🔗 相关链接
📞 联系我们
如有问题或建议,请通过以下方式联系我们:
- 提交 Issue: GitHub Issues
- 提交 PR: GitHub Pull Requests
- 邮箱: [email protected]
XMirror Components - 让前端开发更简单、更高效! 🚀
