Semi Design ConfigProvider 全局配置完全指南:时区、RTL 国际化与响应式断点实战
Semi Design ConfigProvider 全局配置完全指南:时区、RTL 国际化与响应式断点实战
本篇技术指南以 Semi Design(@douyinfe/semi-ui)的 ConfigProvider 全局配置组件为核心,讲解如何通过 React Context 为整棵组件树统一注入时区(timeZone)、文本方向(direction)、多语言(locale)与弹层挂载容器(getPopupContainer)等公共 Props,并覆盖 2.97.0 起新增的响应式断点订阅能力,以及 2.59.0 起提供的 semiGlobal 默认 Props 覆盖方案。读完本文,你将掌握两种全局配置手段的适用边界、完整 API 参数语义、时区标识的内部转换规则,以及它们在仓库源码中的真实实现机制。
使用场景:两种覆盖配置的分工
Semi 将“覆盖配置”划分为两个场景,对应两套不同的 API:
- 需要覆盖多个组件公有的 Props 配置(例如
timeZone、rtl/direction这类跨组件共享的配置项),使用ConfigProvider。它借助 React Context 机制实现,因此能够影响 React 节点树中的全部后代组件,属于“树级、声明式”的全局配置。 - 当
ConfigProvider暴露的参数无法满足需求,希望全局修改某一个组件的某类 Props 时(例如期望将所有Button的theme都配置为solid,或将所有Popover的zIndex统一调高),使用semiGlobal。它属于“站点级、命令式”的默认值覆盖。
两条路线的底层差异可以从源码得到印证:ConfigProvider 是一个基于 React.createContext 的 Provider 组件(见 context.tsx),配置通过 Context 向下传递;而 semiGlobal 是一个导入即用、全局唯一的单例对象(见 semi-global.ts),组件在读取默认 Props 时通过 getDefaultPropsFromGlobalConfig 动态合并(见 _utils/index.tsx)。
如何引入
import { ConfigProvider } from '@douyinfe/semi-ui';
ConfigProvider、ConfigConsumer 以及 semiGlobal 均可直接从 @douyinfe/semi-ui 主入口导入。其中 ConfigConsumer 与 ConfigProvider 共享同一个 Context 定义,ConfigConsumer = Context.Consumer(见 configProvider/index.tsx),用于在无法直接消费 Provider 值的场景下手动读取全局配置。
基本用法:为时间类组件配置时区
通过向 ConfigProvider 传入 timeZone 参数,可以为包裹范围内的 DatePicker、TimePicker 等时间类组件统一配置时区。下面的示例通过 Select 动态切换时区,DatePicker 与 TimePicker 会随之更新显示:
import React, { useMemo, useState } from 'react';
import { ConfigProvider, Select, DatePicker, TimePicker } from '@douyinfe/semi-ui';
function Demo(props = {}) {
const [timeZone, setTimeZone] = useState('GMT+08:00');
const defaultTimestamp = 1581599305265;
const gmtList = useMemo(() => {
const list = [];
for (let hourOffset = -11; hourOffset <= 14 ; hourOffset++) {
const prefix = hourOffset >= 0 ? '+' : '-';
const hOffset = Math.abs(parseInt(hourOffset, 10));
list.push(`GMT${prefix}${String(hOffset).padStart(2, '0')}:00`);
}
return list;
}, []);
return (
<ConfigProvider timeZone={timeZone}>
<div style={{ width: 300 }}>
<h5 style={{ margin: 10 }}>Select Time Zone:</h5>
<Select
placeholder={'Select time zone'}
style={{ width: 300 }}
value={timeZone}
showClear={true}
onSelect={value => setTimeZone(value)}
>
{gmtList.map(gmt => (
<Select.Option key={gmt} value={gmt}>
{gmt}
</Select.Option>
))}
</Select>
<br/>
<br/>
<DatePicker type={'dateTime'} defaultValue={defaultTimestamp} onChange={(date, dateString) => console.log('DatePicker changed: ', date, dateString)} />
<br/>
<br/>
<TimePicker defaultValue={defaultTimestamp} onChange={(date, dateString) => console.log('DatePicker changed: ', date, dateString)} />
</div>
</ConfigProvider>
);
}
从源码看,timeZone 的实际消费发生在组件 foundation 层:DatePicker 的 foundation.ts 在初始化时会调用 parseWithTimezone 将传入值按指定时区解析;TimePicker 的 foundation.ts 同样在解析日期时通过 utcToZonedTime 做时区换算。也就是说,ConfigProvider 只是“搬运”配置,真正的时区语义由各时间组件基于 date-fns-tz 的能力实现。
时区标识(Time Zone Identifier)
timeZone 支持 string | number 两种类型,取值规则如下:
- 数字,例如
1、-9.5,代表距离 UTC 的时间偏移,单位为小时,可以为负数或小数; - 字符串,例如
"GMT-09:30"、"GMT+08:00"这样以"GMT"开头的表征偏移字符串,也可以直接使用 IANA 标识,如"Asia/Shanghai"、"America/Los_Angeles"等。
当你使用数字或 GMT-09:00 类似写法时,Semi 内部会将这些时区标识转换为 IANA 标识:
- 如设置
-9或GMT-09:00时,会转换成Pacific/Gambier。某些数字对应的 IANA 标识可能有多个,Semi 首选**无夏令时(DST)**的 IANA 标识; - 如果该数字没有对应的无夏令时 IANA 标识,如
-3.5、3.5、10.5、13.75,这时映射的就是一个有夏令时的 IANA 标识,有夏令时的时区会在偏移量上进行调整。例如-3.5会在进入夏令时后在标准时间上增加 1 小时。
如果你想准确设置一个地区的时区,推荐直接使用 IANA 标识而不是偏移量写法,并自行确认该时区是否有夏令时(可查阅 IANA 标识列表)。
这一转换逻辑在仓库中由 date-fns-extra.ts 的 toIANA 函数实现:整数偏移优先查 IANAEtcGMTOffsetMap('8' -> 'Etc/GMT-8' 这类无 DST 的 Etc 时区),不匹配再回退到 IANAOffsetMap(如 8.75 -> Australia/Eucla、10.5 -> Australia/Adelaide、13.75 -> Pacific/Chatham)。这正是文档中“首选无 DST 标识、退而求其次才选有 DST 标识”规则的代码来源。
手动获取配置值:ConfigConsumer
通常情况下,组件内部会自动获取并消费 ConfigProvider 的值,无需关心。但在一些特殊场景(例如自定义业务组件需要读取当前时区、方向做额外处理,或需要拿到当前断点状态),你可能需要手动获取这些值。
使用 ConfigConsumer 获取 ConfigProvider 的值:
import React, { useMemo, useState } from 'react';
import { ConfigProvider, ConfigConsumer, Select, DatePicker, TimePicker, Typography } from '@douyinfe/semi-ui';
function Demo(props = {}) {
const [timeZone, setTimeZone] = useState('GMT+08:00');
const defaultTimestamp = 1581599305265;
const gmtList = useMemo(() => {
const list = [];
for (let hourOffset = -11; hourOffset <= 14; hourOffset++) {
const prefix = hourOffset >= 0 ? '+' : '-';
const hOffset = Math.abs(parseInt(hourOffset, 10));
list.push(`GMT${prefix}${String(hOffset).padStart(2, '0')}:00`);
}
return list;
}, []);
return (
<ConfigProvider timeZone={timeZone}>
{/*...*/}
<ConfigConsumer>
{(value) => {
return <Typography.Text ellipsis={{ showTooltip: {opts:{style:{minWidth:"1200px"}} }}} style={{ width: 600 }}>
{JSON.stringify(value)}
</Typography.Text>
}}
</ConfigConsumer>
{/*...*/}
</ConfigProvider>
);
}
ConfigConsumer 的 render-prop 回调收到的 value 即 Context 值对象,其字段定义见 context.tsx:包含 direction、timeZone、locale、getPopupContainer、responsiveMap、onBreakpoint、screens 等。注意 onBreakpoint 与 screens 属于“内部下发”的能力,并不是 ConfigProvider 的公开 Props。
响应式断点监听(>= 2.97.0)
ConfigProvider 支持配置响应式断点,并在断点变化时进行订阅回调。这一能力从 2.97.0 版本开始提供。
注意事项
- 出于性能考虑,
responsiveObserve默认值为false,不开启时不会注册任何matchMedia监听; onBreakpoint/screens不属于ConfigProvider的 props,需要通过ConfigConsumer获取;- 订阅时回调会立即执行一次,传入的就是当前各断点的命中情况,因此你不需要在初始挂载时再单独调用一次
window.matchMedia; responsiveMap是引用比较:如果直接 inline 写对象(每次 render 引用都不同),会被识别为发生变化并重新注册全部监听。建议把它定义在组件外,或使用useMemo保证引用稳定。
开启监听与自定义断点
通过 responsiveObserve 开启断点监听(建议只在确实需要订阅的场景开启),通过 responsiveMap 自定义断点(未传入时使用默认断点):
import React, { useEffect, useState } from 'react';
import { ConfigProvider, ConfigConsumer, Typography } from '@douyinfe/semi-ui';
function BreakpointSubscriber({ onBreakpoint, screens }) {
const [subscribedScreens, setSubscribedScreens] = useState(screens);
useEffect(() => {
if (!onBreakpoint) {
return;
}
const unsubscribe = onBreakpoint(next => {
setSubscribedScreens(next);
});
return unsubscribe;
}, [onBreakpoint]);
return (
<Typography.Text>
{JSON.stringify(subscribedScreens || screens)}
</Typography.Text>
);
}
function Demo() {
return (
<ConfigProvider
responsiveObserve
responsiveMap={{
xs: '(max-width: 575px)',
sm: '(min-width: 576px)',
md: '(min-width: 768px)',
lg: '(min-width: 992px)',
xl: '(min-width: 1200px)',
xxl: '(min-width: 1600px)',
}}
>
<ConfigConsumer>
{({ onBreakpoint, screens }) => (
<BreakpointSubscriber onBreakpoint={onBreakpoint} screens={screens} />
)}
</ConfigConsumer>
</ConfigProvider>
);
}
默认断点映射与上述示例完全一致,并在源码中导出为 ConfigProvider.defaultResponsiveMap(见 configProvider/index.tsx)。断点 key 固定为 xs/sm/md/lg/xl/xxl,类型定义见 responsiveTypes.ts。
订阅 API
onBreakpoint 支持两种签名,均会返回取消订阅函数:
onBreakpoint((screens) => void):回调拿到完整的 screens 映射(BreakpointScreens,即各断点当前是否命中的布尔集合);onBreakpoint(['md', 'lg'], (screen, match) => void):只监听指定断点,回调拿到单个断点及其命中状态。
底层实现机制
从 configProvider/index.tsx 的源码可以看到这一能力的完整生命周期:
- 懒注册:
responsiveObserve开启后,并不会立刻注册监听,而是在第一次出现订阅者(screensListeners或changeListeners非空)时通过ensureMediaQueriesRegistered才真正注册; - 自动注销:当最后一个订阅者取消订阅后(
unregisterMediaQueries),所有matchMedia监听会被移除,避免常驻开销; - 立即回调:注册时同步读取一次各断点的
matches写入currentScreensRef,订阅回调立即拿到当前快照,不需要自行调用window.matchMedia; - 引用比较:
componentDidUpdate中对prevProps.responsiveMap !== this.props.responsiveMap做引用级比较,变化即触发重新注册——这正是“inline 对象每次 render 都会重注册”的原因; - 媒体查询工具:底层使用
_utils中封装的 registerMediaQuery,优先走MediaQueryList.addEventListener,并兼容旧式addListener接口。
另外需要留意:如果在未开启 responsiveObserve 时调用 onBreakpoint 订阅,源码会输出一条开发警告,提示你开启该开关(见 configProvider/index.tsx)。
RTL / LTR 文本方向国际化
全局配置 direction 可以改变组件的文本方向(自 1.8.0 起提供)。rtl 表示从右到左(类似希伯来语或阿拉伯语),ltr 表示从左到右(类似中文、英语等大部分语言)。从源码看,当 direction === 'rtl' 时,ConfigProvider 会用 semi-rtl class 包裹子节点(见 configProvider/index.tsx),各组件在此基础上配合 SCSS 完成镜像布局。
特殊组件说明
- Modal、Notification、Toast 的命令式调用需要通过 prop 传
direction(因为命令式调用不在组件树内,Context 无法透传,需在调用参数中显式指定); - 有方向性的 Icon 的 RTL 适配需要自行处理——Semi 认为对 Icon 做 RTL 会使其难以理解和维护,其他组件内的 icon Semi 已经做了 RTL 适配;
- Table 的树形数据暂不支持 RTL(Chrome、Safari 浏览器表现与 Firefox 表现不同),固定列在 v2.32 版本开始支持 RTL。
完整演示
下面的综合示例在一个 ConfigProvider direction={direction} locale={en_GB} 中展示 RTL 切换后各类组件的表现,同时演示了命令式组件如何通过 prop 传入 direction:
import React, { useState } from 'react';
import { ConfigProvider, ButtonGroup, Button, Row, Col, Notification, DatePicker, TimePicker, Timeline, Popover, Tag, Tooltip, Badge, Avatar, Steps, Pagination, Modal, Breadcrumb, Rating, Nav, Spin, Cascader, Radio, Select, Input, Typography, TextArea, Checkbox, Switch } from '@douyinfe/semi-ui';
import { IconVigoLogo, IconEdit, IconCamera, IconList, IconSidebar, IconChevronDown } from '@douyinfe/semi-icons';
import en_GB from '@douyinfe/semi-ui/locale/source/en_GB';
function Demo(props = {}) {
const { Option } = Select;
const [direction, setDirection] = useState();
const flexStyle = { display: 'flex', marginBottom: 32, flexWrap: 'wrap' };
const titleStyle = { margin: '50px 0 16px 0' };
const rowStyle = { margin: '16px 10px' };
const badgeStyle = {
width: '42px',
height: '42px',
borderRadius: '4px',
display: 'inline-block',
};
const tagStyle = { marginRight: 8, marginBottom: 8 };
const buttonStyle = { ...tagStyle };
const opts = {
title: 'Hi,Bytedance',
content: 'ies dance dance dance',
duration: 3,
direction, // 命令式调用必须通过 prop 传 direction
};
const treeData = [
{
label: 'Zhejiang',
value: 'zhejiang',
children: [
{
label: 'Hangzhou',
value: 'hangzhou',
children: [
{ label: 'Xihu', value: 'xihu' },
{ label: 'Xianhan', value: 'xiaoshan' },
{ label: 'Lin’an', value: 'linan' },
],
},
{
label: 'Ningbo',
value: 'ningbo',
children: [
{ label: 'Haishu', value: 'haishu' },
{ label: 'Jiangbei', value: 'jiangbei' }
]
},
],
}
];
return (
<div>
<div style={{ marginBottom: 20 }}>
<ButtonGroup>
<Button onClick={() => setDirection('ltr')}>LTR</Button>
<Button onClick={() => setDirection('rtl')}>RTL</Button>
</ButtonGroup>
</div>
<ConfigProvider direction={direction} locale={en_GB}>
<Row>
<h3 style={titleStyle}>Buttons</h3>
</Row>
<Row style={rowStyle}>
<Button loading={true} theme="solid" style={{ marginRight: 8 }}>Loading</Button>
<Button icon={<IconSidebar />} theme="solid" style={{ marginRight: 8 }}>Collapsing</Button>
<Button icon={<IconChevronDown />} theme="solid" iconPosition={"right"} style={{ marginRight: 8 }}>Expand options</Button >
<br/><br/>
<ButtonGroup>
<Button>Copy</Button>
<Button>Query</Button>
<Button>Cut</Button>
</ButtonGroup>
</Row>
<Row>
<h3 style={titleStyle}>Input</h3>
</Row>
<Row style={rowStyle} gutter={16}>
<Col span={12}>
<Input placeholder='Input something'></Input>
<br/><br/>
<Input disabled placeholder='Input something'></Input>
<br/><br/>
<Input prefix="Prefix" showClear></Input>
<br/><br/>
<Input suffix={<Typography.Text strong type='secondary' style={{ margin: '0 8px' }}>Suffix</Typography.Text>} showClear></Input>
<br/><br/>
<TextArea placeholder="Input something" maxCount={100} />
<br/><br/>
<div style={flexStyle}>
<Switch style={{ marginRight: 8 }} defaultChecked={true}></Switch>
<Switch style={{ marginRight: 8 }}></Switch>
<Switch disabled defaultChecked={true} style={{ marginRight: 8 }}></Switch>
</div>
<div style={flexStyle}>
<Checkbox style={{ marginRight: 8 }} defaultChecked>Checkbox</Checkbox>
<Checkbox style={{ marginRight: 8 }} disabled defaultChecked>Disabled Checkbox</Checkbox>
<Checkbox style={{ marginRight: 8 }} disabled>Disabled Checkbox</Checkbox>
</div>
<div style={{ ...flexStyle, marginBottom: 0 }}>
<Radio style={{ marginRight: 8 }} defaultChecked>Radio</Radio>
<Radio style={{ marginRight: 8 }} disabled defaultChecked>Disabled Radio</Radio>
<Radio style={{ marginRight: 8 }} disabled>Disabled Radio</Radio>
</div>
</Col>
<Col span={12}>
<DatePicker onChange={(date, dateString) => console.log(dateString)} style={{ width: '100%' }}/>
<br/><br/>
<TimePicker style={{ width: '100%' }} />
<br/><br/>
<Select style={{ width: '100%' }} placeholder="Select-single">
<Option value='abc'>Semi</Option>
<Option value='hotsoon'>Hotsoon</Option>
<Option value='pipixia' disabled>Pipixia</Option>
<Option value='xigua'>Xigua</Option>
</Select>
<br/><br/>
<Select disabled style={{ width: '100%' }} placeholder="Select-disabled">
<Option value='abc'>Semi</Option>
<Option value='hotsoon'>Hotsoon</Option>
<Option value='pipixia' disabled>Pipixia</Option>
<Option value='xigua'>Xigua</Option>
</Select>
<br/><br/>
<Select multiple style={{ width: '100%' }} placeholder="Select-mutiple">
<Option value='abc'>Semi</Option>
<Option value='hotsoon'>Hotsoon</Option>
<Option value='pipixia' disabled>Pipixia</Option>
<Option value='xigua'>Xigua</Option>
</Select>
<br/><br/>
<Cascader style={{ width: '100%' }} treeData={treeData} placeholder="Cascader"/>
</Col>
</Row>
<Row>
<h3 style={titleStyle}>Navigation</h3>
</Row>
<Row style={rowStyle}>
<Breadcrumb>
<Breadcrumb.Item>Semi-ui</Breadcrumb.Item>
<Breadcrumb.Item>Breadcrumb</Breadcrumb.Item>
<Breadcrumb.Item>Default</Breadcrumb.Item>
</Breadcrumb>
<Nav
mode={'horizontal'}
items={[
{ itemKey: 'user', text: 'Option1', icon: <IconEdit /> },
{ itemKey: 'union', text: 'Option2', icon: <IconCamera /> },
{
itemKey: 'approve-management',
text: 'Group3',
icon: <IconList />,
items: ['3-1', '3-2']
},
]}
/>
<br/><br/>
<Pagination total={80} showSizeChanger></Pagination>
<br/>
<Steps current={1}>
<Steps.Step title="Finished" description="This is a description." />
<Steps.Step title="In Progress" description="This is a description." />
<Steps.Step title="Waiting" description="This is a description." />
</Steps>
<br/>
<Steps current={1} status="error">
<Steps.Step title="Finished" description="This is a description" />
<Steps.Step title="In Process" description="This is a description" />
<Steps.Step title="Waiting" description="This is a description" />
</Steps>
</Row>
<Row>
<h3 style={titleStyle}>Display</h3>
</Row>
<Row style={rowStyle}>
<div style={{ display: 'flex' }}>
<div style={{ padding: 8 }}>
<Badge count={5} theme='solid' >
<Avatar color='blue' shape='square' style={badgeStyle}>XZ</Avatar>
</Badge>
</div>
<div style={{ padding: 8 }}>
<Badge count={5} theme='light' >
<Avatar color='cyan' shape='square' style={badgeStyle}>YB</Avatar>
</Badge>
</div>
<div style={{ padding: 8 }}>
<Badge count={5} theme='inverted'>
<Avatar color='indigo' shape='square' style={badgeStyle}>LX</Avatar>
</Badge>
</div>
<div style={{ padding: 8 }}>
<Badge dot theme='solid' >
<Avatar color='light-blue' shape='square' style={badgeStyle}>YZ</Avatar>
</Badge>
</div>
<div style={{ padding: 8 }}>
<Badge dot theme='light' >
<Avatar color='teal' shape='square' style={badgeStyle}>HW</Avatar>
</Badge>
</div>
<div style={{ padding: '8px', borderRadius: '4px', backgroundColor: 'var(--semi-color-fill-0)' }}>
<Badge dot theme='inverted'>
<Avatar color='green' shape='square' style={badgeStyle}>XM</Avatar>
</Badge>
</div>
</div>
<br/>
<div>
<Tag color='grey' style={tagStyle}> grey tag </Tag>
<Tag color='blue' style={tagStyle}> blue tag </Tag>
<Tag color='blue' type='ghost' style={tagStyle}> ghost tag </Tag>
<Tag color='blue' type='solid' style={tagStyle}> solid tag </Tag>
<Tag color='red' style={tagStyle}> red tag </Tag>
<Tag color='green' style={tagStyle}> green tag </Tag>
<Tag color='orange' style={tagStyle}> orange tag </Tag>
<Tag color='teal' style={tagStyle}> teal tag </Tag>
<Tag color='violet' style={tagStyle}> violet tag </Tag>
<Tag color='white' style={tagStyle}> white tag </Tag>
</div>
<br/>
<div style={{ display: 'flex', alignItems: 'center' }}>
<Popover content={'hi semi-design'} style={{ padding: 8 }}><Tag style={{ marginRight: 8 }}>I am Popover</Tag></Popover>
<Tooltip content={'hi semi-design'}>
<Tag style={{ marginRight: 8 }}>I am Tooltip</Tag>
</Tooltip>
<Rating defaultValue={3} size='small' style={{ marginRight: 8 }} />
</div>
<br/>
<Timeline>
<Timeline.Item time='2019-07-14 10:35' type='ongoing'>Under review</Timeline.Item>
<Timeline.Item time='2019-06-13 16:17' type='success'>Publish successfully</Timeline.Item>
<Timeline.Item time='2019-05-14 18:34' type='error'>Audit failure</Timeline.Item>
</Timeline>
</Row>
<Row>
<h3 style={titleStyle}>Feedback</h3>
</Row>
<Row style={rowStyle}>
<Button type='primary' onClick={() => Notification.success(opts)} style={buttonStyle}>Notification of success information</Button>
<Button onClick={() => Notification.info(opts)} style={buttonStyle}>Notification of prompt information</Button>
<Button type="warning" onClick={() => Notification.warning(opts)} style={buttonStyle}>Notification of warning information</Button>
<Button type="danger" onClick={() => Notification.error(opts)} style={buttonStyle}>Notification of failure information</Button>
<Button
style={buttonStyle}
ghost={false}
icon={<IconVigoLogo />}
onClick={() => Notification.info({ ...opts, icon: <IconVigoLogo /> })}
/>
<Button
style={buttonStyle}
ghost={false}
icon={<IconVigoLogo />}
onClick={() => Notification.info({ ...opts, icon: <IconVigoLogo style={{ color: 'pink' }} /> })}
/>
<br/>
<Button type='primary' onClick={() => Modal.success(opts)} style={buttonStyle}>Modal of success information</Button>
<Button onClick={() => Modal.info(opts)} style={buttonStyle}>Modal of prompt information</Button>
<Button type="warning" onClick={() => Modal.warning(opts)} style={buttonStyle}>Modal of warning information</Button>
<Button type="danger" onClick={() => Modal.error(opts)} style={buttonStyle}>Modal of failure information</Button>
<br/>
<Button type='primary' onClick={() => Toast.success(opts)} style={buttonStyle}>Toast of success information</Button>
<Button onClick={() => Toast.info(opts)} style={buttonStyle}>Toast of prompt information</Button>
<Button type="warning" onClick={() => Toast.warning(opts)} style={buttonStyle}>Toast of waning information</Button>
<Button type="danger" onClick={() => Toast.error(opts)} style={buttonStyle}>Toast of failure information</Button>
<br/><br/>
<Spin tip='I am loading...'>
<div style={{
backgroundColor: 'var(--semi-color-primary-light-default',
border: '1px solid var(--semi-color-primary)',
borderRadius: '4px',
padding: '16px 10px'
}}>
<p>Here are some texts.</p>
<p>And more texts on the way.</p>
</div>
</Spin>
</Row>
</ConfigProvider>
</div>
);
}
API 参考
| 属性 | 说明 | 类型 | 默认值 |
|---|---|---|---|
| direction | 设置文本的方向 | ltr | rtl |
ltr |
| responsiveObserve | 是否开启响应式断点监听。默认关闭以避免全局注册 matchMedia 带来的性能开销;开启后在首次订阅时懒注册监听,无订阅时会自动注销,>= 2.97.0 |
boolean | false |
| responsiveMap | 自定义断点配置,key 为 xs/sm/md/lg/xl/xxl,value 为 media query 字符串;未传入时使用默认断点(可通过 ConfigProvider.defaultResponsiveMap 获取),>= 2.97.0 |
object | — |
| getPopupContainer | 指定父级 DOM,弹层将会渲染至该 DOM 中,自定义时需要设置 position: relative。这会改变浮层 DOM 树位置,但不会改变视图渲染位置。 |
function(): HTMLElement | () => document.body |
| locale | 多语言配置,与 LocaleProvider 中 locale 参数的用法一致(如果同时在 ConfigProvider 和 LocaleProvider 中配置 locale,前者优先级高于后者) |
object | — |
| timeZone | 时区标识 | string | number | — |
补充说明:locale 的取值来自 @douyinfe/semi-ui/locale/source 下的语言包(如 en_GB、zh_CN 等,locale/source 目录下提供数十种语言)。源码中 ConfigProvider 的 defaultProps 将 locale 默认为中文语言包、direction 默认为 'ltr'、responsiveObserve 默认为 false(见 configProvider/index.tsx)。
FAQ:如何全局自定义 prefixCls
ConfigProvider 没有提供全局自定义 prefix classname 的功能。如果有类似需求(例如在 SDK 中使用 Semi,期望打包的 DOM 样式不带 .semi-xx 前缀,以免被宿主页面的全局 CSS 影响),可以参考以下方案:
- 由于
prefixCls需要同时被组件层的 JS/CSS 消费,Semi 将这个开关放在了 webpack plugin 的配置项中,而不是作为ConfigProvider的配置项; - 如果使用 webpack,请在
SemiWebpackPlugin的参数中进行配置:
# webpack config example: webpack.config.js
const SemiWebpackPlugin = require('@douyinfe/semi-webpack-plugin').default;
module.exports = {
+ plugins: [new SemiWebpackPlugin({ prefixCls: 'imes' })],
}
该插件的源码位于仓库 packages/semi-webpack(另有对应的 semi-rspack 与 semi-vite 等构建插件,可满足不同构建工具链的前缀定制需求)。
semiGlobal:全局覆盖组件默认 Props(>= 2.59.0)
除了 ConfigProvider,你还可以通过 semiGlobal 配置覆盖全局组件的默认 Props。该能力在 v2.59.0 之后提供。
在 semiGlobal.config.overrideDefaultProps 中可配置组件默认 Props,你需要将配置放到整个站点的入口处,即保证它优先于所有 Semi 组件执行。
注意:
semiGlobal是单例模式,会影响整个站点。如果只想覆盖某些地方的某些组件 Props,建议不要使用semiGlobal,而是将对应需要覆盖的组件封装一层并传入修改后的默认 props。
例如下方配置将所有的 Button 默认设置为 warning、Select 的 zIndex 默认设置为 2000、Tooltip 默认以 click 触发:
import { semiGlobal } from "@douyinfe/semi-ui";
semiGlobal.config.overrideDefaultProps = {
Select: {
zIndex: 2000,
},
Tooltip: {
zIndex: 2001,
trigger: 'click'
},
};
实现机制与支持范围
从源码可以进一步理解该能力的边界:
- 单例结构:
semiGlobal是SemiGlobal类的默认导出实例(export default new SemiGlobal()),其config上除overrideDefaultProps外还承载了createRoot等 React 19 兼容配置(见 semi-global.ts); - 覆盖组件清单:
overrideDefaultProps的类型定义覆盖了约 40 个组件,包括Button、Select、Tooltip、Input、DatePicker、TimePicker、Table、Tree、Popover、Modal、Notification、Toast、Spin、Typography等(完整列表见 semi-global.ts); - 动态合并:各组件在声明默认 Props 时调用
getDefaultPropsFromGlobalConfig(componentName, semiDefaultProps),返回一个基于Proxy的默认 Props 对象,读取属性时优先返回semiGlobal.config.overrideDefaultProps中配置的值(见 _utils/index.tsx),因此组件级显式传入的 Props 仍然拥有最高优先级; - 健壮性:Proxy 对
Object.freeze/Object.seal冻结的配置对象做了兼容处理(getOwnPropertyDescriptor中保持描述符可配置),这一行为有对应单元测试覆盖(见 _utils/test/overrideDefaultProps.test.js)。
小结:如何选择全局配置方案
| 维度 | ConfigProvider | semiGlobal |
|---|---|---|
| 机制 | React Context(树级注入) | 单例 + Proxy 默认值合并(站点级) |
| 适用场景 | 覆盖多组件公有 Props(timeZone、direction、locale、getPopupContainer、断点) |
覆盖某个组件的某类 Props(如所有 Button.theme、所有 Popover.zIndex) |
| 作用范围 | Provider 包裹的子树 | 整个站点(全局单例) |
| 优先级 | Context 值在组件内被消费 | 低于组件显式 props,高于组件内置 defaultProps |
| 引入版本 | 长期提供 | 2.59.0 起 |
实际项目中,通常以 ConfigProvider 作为应用根级别的统一配置入口(时区、语言、方向、弹层容器),再配合 semiGlobal 对个别组件做站级默认值兜底;若某个区域需要与全局不同的行为,则应优先考虑组件树级别的局部覆盖或组件封装,避免 semiGlobal 单例带来的全局副作用。