ConfigProvider全局化配置
为组件提供统一的全局化配置。
使用
ConfigProvider 使用 React 的 context 特性,只需在应用外围包裹一次即可全局生效。
import { ConfigProvider } from 'antd';
// ...
return (
<ConfigProvider {...yourConfig}>
<App />
</ConfigProvider>
);
Content Security Policy
部分组件为了支持波纹效果,使用了动态样式。如果开启了 Content Security Policy (CSP),你可以通过 csp
属性来进行配置:
<ConfigProvider csp={{ nonce: 'YourNonceCode' }}>
<Button>My Button</Button>
</ConfigProvider>
代码演示
此处列出 Ant Design 中需要国际化支持的组件,你可以在演示里切换语言。
import {
ConfigProvider,
Pagination,
DatePicker,
TimePicker,
Calendar,
Popconfirm,
Table,
Modal,
Button,
Select,
Transfer,
Radio,
} from 'antd';
import enUS from 'antd/es/locale/en_US';
import zhCN from 'antd/es/locale/zh_CN';
import moment from 'moment';
import 'moment/locale/zh-cn';
moment.locale('en');
const { Option } = Select;
const { RangePicker } = DatePicker;
const columns = [
{
title: 'Name',
dataIndex: 'name',
filters: [
{
text: 'filter1',
value: 'filter1',
},
],
},
{
title: 'Age',
dataIndex: 'age',
},
];
class Page extends React.Component {
state = {
visible: false,
};
showModal = () => {
this.setState({ visible: true });
};
hideModal = () => {
this.setState({ visible: false });
};
render() {
const info = () => {
Modal.info({
title: 'some info',
content: 'some info',
});
};
const confirm = () => {
Modal.confirm({
title: 'some info',
content: 'some info',
});
};
return (
<div className="locale-components">
<div className="example">
<Pagination defaultCurrent={1} total={50} showSizeChanger />
</div>
<div className="example">
<Select showSearch style={{ width: 200 }}>
<Option value="jack">jack</Option>
<Option value="lucy">lucy</Option>
</Select>
<DatePicker />
<TimePicker />
<RangePicker style={{ width: 200 }} />
</div>
<div className="example">
<Button type="primary" onClick={this.showModal}>
Show Modal
</Button>
<Button onClick={info}>Show info</Button>
<Button onClick={confirm}>Show confirm</Button>
<Popconfirm title="Question?">
<a href="#">Click to confirm</a>
</Popconfirm>
</div>
<div className="example">
<Transfer dataSource={[]} showSearch targetKeys={[]} render={item => item.title} />
</div>
<div className="site-config-provider-calendar-wrapper">
<Calendar fullscreen={false} value={moment()} />
</div>
<div className="example">
<Table dataSource={[]} columns={columns} />
</div>
<Modal title="Locale Modal" visible={this.state.visible} onCancel={this.hideModal}>
<p>Locale Modal</p>
</Modal>
</div>
);
}
}
class App extends React.Component {
constructor() {
super();
this.state = {
locale: enUS,
};
}
changeLocale = e => {
const localeValue = e.target.value;
this.setState({ locale: localeValue });
if (!localeValue) {
moment.locale('en');
} else {
moment.locale('zh-cn');
}
};
render() {
const { locale } = this.state;
return (
<div>
<div className="change-locale">
<span style={{ marginRight: 16 }}>Change locale of components: </span>
<Radio.Group value={locale} onChange={this.changeLocale}>
<Radio.Button key="en" value={enUS}>
English
</Radio.Button>
<Radio.Button key="cn" value={zhCN}>
中文
</Radio.Button>
</Radio.Group>
</div>
<ConfigProvider locale={locale}>
<Page
key={locale ? locale.locale : 'en' /* Have to refresh for production environment */}
/>
</ConfigProvider>
</div>
);
}
}
ReactDOM.render(<App />, mountNode);
.site-config-provider-calendar-wrapper {
width: 319px;
border: 1px solid #d9d9d9;
border-radius: 2px;
}
.locale-components {
border-top: 1px solid #d9d9d9;
padding-top: 16px;
}
.code-box-demo .example {
margin: 16px 0;
}
.code-box-demo .example > * {
margin-right: 8px;
}
.change-locale {
margin-bottom: 16px;
}
这里列出了支持 rtl
方向的组件,您可以在演示中切换方向。
import {
Input,
Col,
Row,
Select,
InputNumber,
ConfigProvider,
Cascader,
Radio,
Switch,
Tree,
TreeSelect,
Modal,
Button,
Pagination,
Steps,
Rate,
Badge,
} from 'antd';
import {
SearchOutlined as SearchIcon,
SmileOutlined,
DownloadOutlined,
LeftOutlined,
RightOutlined,
MinusOutlined,
PlusOutlined,
} from '@ant-design/icons';
const InputGroup = Input.Group;
const ButtonGroup = Button.Group;
const { Option } = Select;
const { TreeNode } = Tree;
const { Search } = Input;
const { Step } = Steps;
const cascaderOptions = [
{
value: 'tehran',
label: 'تهران',
children: [
{
value: 'tehran-c',
label: 'تهران',
children: [
{
value: 'saadat-abad',
label: 'سعادت آیاد',
},
],
},
],
},
{
value: 'ardabil',
label: 'اردبیل',
children: [
{
value: 'ardabil-c',
label: 'اردبیل',
children: [
{
value: 'primadar',
label: 'پیرمادر',
},
],
},
],
},
{
value: 'gilan',
label: 'گیلان',
children: [
{
value: 'rasht',
label: 'رشت',
children: [
{
value: 'district-3',
label: 'منطقه ۳',
},
],
},
],
},
];
class Page extends React.Component {
state = {
currentStep: 0,
modalVisible: false,
badgeCount: 5,
showBadge: true,
};
selectBefore = (
<Select defaultValue="Http://" style={{ width: 90 }}>
<Option value="Http://">Http://</Option>
<Option value="Https://">Https://</Option>
</Select>
);
selectAfter = (
<Select defaultValue=".com" style={{ width: 80 }}>
<Option value=".com">.com</Option>
<Option value=".jp">.jp</Option>
<Option value=".cn">.cn</Option>
<Option value=".org">.org</Option>
</Select>
);
// ==== Cascader ====
cascaderFilter = (inputValue, path) => {
return path.some(option => option.label.toLowerCase().indexOf(inputValue.toLowerCase()) > -1);
};
onCascaderChange = value => {
console.log(value);
};
// ==== End Cascader ====
// ==== Modal ====
showModal = () => {
this.setState({
modalVisible: true,
});
};
handleOk = e => {
console.log(e);
this.setState({
modalVisible: false,
});
};
handleCancel = e => {
console.log(e);
this.setState({
modalVisible: false,
});
};
// ==== End Modal ====
onStepsChange = currentStep => {
console.log('onChange:', currentStep);
this.setState({ currentStep });
};
// ==== Badge ====
increaseBadge = () => {
const badgeCount = this.state.badgeCount + 1;
this.setState({ badgeCount });
};
declineBadge = () => {
let badgeCount = this.state.badgeCount - 1;
if (badgeCount < 0) {
badgeCount = 0;
}
this.setState({ badgeCount });
};
onChangeBadge = showBadge => {
this.setState({ showBadge });
};
// ==== End Badge ====
render() {
const { currentStep } = this.state;
return (
<div className="direction-components example">
<Row>
<Col span={24}>
<h3 className="demo-block-title">Cascader example:</h3>
<Cascader
suffixIcon={<SearchIcon />}
options={cascaderOptions}
onChange={this.onCascaderChange}
placeholder="یک مورد انتخاب کنید"
popupPlacement={this.props.popupPlacement}
/>
With search:
<Cascader
suffixIcon={<SmileOutlined />}
options={cascaderOptions}
onChange={this.onCascaderChange}
placeholder="Select an item"
popupPlacement={this.props.popupPlacement}
showSearch={this.cascaderFilter}
/>
</Col>
</Row>
<br />
<Row>
<Col span={12}>
<h3 className="demo-block-title">Switch example:</h3>
<Switch defaultChecked />
<Switch loading defaultChecked />
<Switch size="small" loading />
</Col>
<Col span={12}>
<h3 className="demo-block-title">Radio Group example:</h3>
<Radio.Group defaultValue="c" buttonStyle="solid">
<Radio.Button value="a">تهران</Radio.Button>
<Radio.Button value="b" disabled>
اصفهان
</Radio.Button>
<Radio.Button value="c">فارس</Radio.Button>
<Radio.Button value="d">خوزستان</Radio.Button>
</Radio.Group>
</Col>
</Row>
<br />
<Row>
<Col span={12}>
<h3 className="demo-block-title">Button example:</h3>
<div className="button-demo">
<Button type="primary" icon={<DownloadOutlined />} />
<Button type="primary" shape="circle" icon={<DownloadOutlined />} />
<Button type="primary" shape="round" icon={<DownloadOutlined />} />
<Button type="primary" shape="round" icon={<DownloadOutlined />}>
Download
</Button>
<Button type="primary" icon={<DownloadOutlined />}>
Download
</Button>
<br />
<Button.Group>
<Button type="primary">
<LeftOutlined />
Backward
</Button>
<Button type="primary">
Forward
<RightOutlined />
</Button>
</Button.Group>
<Button type="primary" loading>
Loading
</Button>
<Button type="primary" size="small" loading>
Loading
</Button>
</div>
</Col>
<Col span={12}>
<h3 className="demo-block-title">Tree example:</h3>
<Tree
showLine
checkable
defaultExpandedKeys={['0-0-0', '0-0-1']}
defaultSelectedKeys={['0-0-0', '0-0-1']}
defaultCheckedKeys={['0-0-0', '0-0-1']}
>
<TreeNode title="parent 1" key="0-0">
<TreeNode title="parent 1-0" key="0-0-0" disabled>
<TreeNode title="leaf" key="0-0-0-0" disableCheckbox />
<TreeNode title="leaf" key="0-0-0-1" />
</TreeNode>
<TreeNode title="parent 1-1" key="0-0-1">
<TreeNode title={<span style={{ color: '#1890ff' }}>sss</span>} key="0-0-1-0" />
</TreeNode>
</TreeNode>
</Tree>
</Col>
</Row>
<br />
<Row>
<Col span={24}>
<h3 className="demo-block-title">Input (Input Group) example:</h3>
<InputGroup size="large">
<Row gutter={8}>
<Col span={5}>
<Input defaultValue="0571" />
</Col>
<Col span={8}>
<Input defaultValue="26888888" />
</Col>
</Row>
</InputGroup>
<br />
<InputGroup compact>
<Input style={{ width: '20%' }} defaultValue="0571" />
<Input style={{ width: '30%' }} defaultValue="26888888" />
</InputGroup>
<br />
<InputGroup compact>
<Select defaultValue="Option1">
<Option value="Option1">Option1</Option>
<Option value="Option2">Option2</Option>
</Select>
<Input style={{ width: '50%' }} defaultValue="input content" />
<InputNumber />
</InputGroup>
<br />
<Search placeholder="input search text" enterButton="Search" size="large" />
<br />
<br />
<div style={{ marginBottom: 16 }}>
<Input
addonBefore={this.selectBefore}
addonAfter={this.selectAfter}
defaultValue="mysite"
/>
</div>
<br />
<Row>
<Col span={12}>
<h3 className="demo-block-title">Select example:</h3>
<Select mode="multiple" defaultValue="مورچه" style={{ width: 120 }}>
<Option value="jack">Jack</Option>
<Option value="مورچه">مورچه</Option>
<Option value="disabled" disabled>
Disabled
</Option>
<Option value="Yiminghe">yiminghe</Option>
</Select>
<Select defaultValue="مورچه" style={{ width: 120 }} disabled>
<Option value="مورچه">مورچه</Option>
</Select>
<Select defaultValue="مورچه" style={{ width: 120 }} loading>
<Option value="مورچه">مورچه</Option>
</Select>
<Select
showSearch
style={{ width: 200 }}
placeholder="Select a person"
optionFilterProp="children"
filterOption={(input, option) =>
option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
}
>
<Option value="jack">Jack</Option>
<Option value="سعید">سعید</Option>
<Option value="tom">Tom</Option>
</Select>
</Col>
<Col span={12}>
<h3 className="demo-block-title">TreeSelect example:</h3>
<div>
<TreeSelect
showSearch
style={{ width: '100%' }}
dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
placeholder="Please select"
allowClear
treeDefaultExpandAll
>
<TreeNode value="parent 1" title="parent 1" key="0-1">
<TreeNode value="parent 1-0" title="parent 1-0" key="0-1-1">
<TreeNode value="leaf1" title="my leaf" key="random" />
<TreeNode value="leaf2" title="your leaf" key="random1" />
</TreeNode>
<TreeNode value="parent 1-1" title="parent 1-1" key="random2">
<TreeNode
value="sss"
title={<b style={{ color: '#08c' }}>sss</b>}
key="random3"
/>
</TreeNode>
</TreeNode>
</TreeSelect>
</div>
</Col>
</Row>
<br />
<Row>
<Col span={24}>
<h3 className="demo-block-title">Modal example:</h3>
<div>
<Button type="primary" onClick={this.showModal}>
Open Modal
</Button>
<Modal
title="پنچره ساده"
visible={this.state.modalVisible}
onOk={this.handleOk}
onCancel={this.handleCancel}
>
<p>نگاشتههای خود را اینجا قراردهید</p>
<p>نگاشتههای خود را اینجا قراردهید</p>
<p>نگاشتههای خود را اینجا قراردهید</p>
</Modal>
</div>
</Col>
</Row>
<br />
<Row>
<Col span={24}>
<h3 className="demo-block-title">Steps example:</h3>
<div>
<Steps progressDot current={currentStep}>
<Step title="Finished" description="This is a description." />
<Step title="In Progress" description="This is a description." />
<Step title="Waiting" description="This is a description." />
</Steps>
<br />
<Steps current={currentStep} onChange={this.onStepsChange}>
<Step title="Step 1" description="This is a description." />
<Step title="Step 2" description="This is a description." />
<Step title="Step 3" description="This is a description." />
</Steps>
</div>
</Col>
</Row>
<br />
<Row>
<Col span={12}>
<h3 className="demo-block-title">Rate example:</h3>
<div>
<Rate defaultValue={2.5} />
<br />
<strong>* Note:</strong> Half star not implemented in RTL direction, it will be
supported after <a href="https://github.com/react-component/rate">rc-rate</a>{' '}
implement rtl support.
</div>
</Col>
<Col span={12}>
<h3 className="demo-block-title">Badge example:</h3>
<div>
<div>
<Badge count={this.state.badgeCount}>
<a href="#" className="head-example" />
</Badge>
<ButtonGroup>
<Button onClick={this.declineBadge}>
<MinusOutlined />
</Button>
<Button onClick={this.increaseBadge}>
<PlusOutlined />
</Button>
</ButtonGroup>
</div>
<div style={{ marginTop: 10 }}>
<Badge dot={this.state.showBadge}>
<a href="#" className="head-example" />
</Badge>
<Switch onChange={this.onChangeBadge} checked={this.state.showBadge} />
</div>
</div>
</Col>
</Row>
</Col>
</Row>
<br />
<br />
<Row>
<Col span={24}>
<h3 className="demo-block-title">Pagination example:</h3>
<Pagination showSizeChanger defaultCurrent={3} total={500} />
</Col>
</Row>
<br />
<Row>
<Col span={24}>
<h3 className="demo-block-title">Grid System example:</h3>
<div className="grid-demo">
<div className="code-box-demo">
<p>
<strong>* Note:</strong> Every calculation in RTL grid system is from right side
(offset, push, etc.)
</p>
<Row>
<Col span={8}>col-8</Col>
<Col span={8} offset={8}>
col-8
</Col>
</Row>
<Row>
<Col span={6} offset={6}>
col-6 col-offset-6
</Col>
<Col span={6} offset={6}>
col-6 col-offset-6
</Col>
</Row>
<Row>
<Col span={12} offset={6}>
col-12 col-offset-6
</Col>
</Row>
<Row>
<Col span={18} push={6}>
col-18 col-push-6
</Col>
<Col span={6} pull={18}>
col-6 col-pull-18
</Col>
</Row>
</div>
</div>
</Col>
</Row>
</div>
);
}
}
class App extends React.Component {
state = {
direction: 'ltr',
popupPlacement: 'bottomLeft',
};
changeDirection = e => {
const directionValue = e.target.value;
this.setState({ direction: directionValue });
if (directionValue === 'rtl') {
this.setState({ popupPlacement: 'bottomRight' });
} else {
this.setState({ popupPlacement: 'bottomLeft' });
}
};
render() {
const { direction } = this.state;
return (
<div>
<div className="change-direction">
<span style={{ marginRight: 16 }}>Change direction of components: </span>
<Radio.Group defaultValue="ltr" onChange={this.changeDirection}>
<Radio.Button key="ltr" value="ltr">
LTR
</Radio.Button>
<Radio.Button key="rtl" value="rtl">
RTL
</Radio.Button>
</Radio.Group>
</div>
<ConfigProvider direction={direction}>
<Page className={direction} popupPlacement={this.state.popupPlacement} />
</ConfigProvider>
</div>
);
}
}
ReactDOM.render(<App />, mountNode);
.direction-components {
padding-top: 16px;
border-top: 1px solid rgba(150, 150, 150, 0.5);
}
.example {
margin: 16px 0;
}
.example > * {
margin-right: 8px;
}
.change-direction {
margin-bottom: 16px;
}
.demo-block-title {
margin: 0 8px 18px 8px;
border-bottom: 1px solid rgba(150, 150, 150, 0.5);
}
.button-demo .ant-btn,
.button-demo .ant-btn-group {
margin-right: 8px;
margin-bottom: 12px;
}
.button-demo .ant-btn-group > .ant-btn,
.button-demo .ant-btn-group > span > .ant-btn {
margin-right: 0;
margin-left: 0;
}
.head-example {
display: inline-block;
width: 42px;
height: 42px;
vertical-align: middle;
background: #eee;
border-radius: 4px;
}
.ant-badge:not(.ant-badge-not-a-wrapper) {
margin-right: 20px;
}
.ant-badge-rtl:not(.ant-badge-not-a-wrapper) {
margin-right: 0;
margin-left: 20px;
}
修改默认组件尺寸。
import React, { useState } from 'react';
import {
ConfigProvider,
Radio,
Input,
Button,
Select,
DatePicker,
Divider,
Table,
Card,
} from 'antd';
const FormSizeDemo = () => {
const [componentSize, setComponentSize] = useState('small');
return (
<div>
<Radio.Group
value={componentSize}
onChange={e => {
setComponentSize(e.target.value);
}}
>
<Radio.Button value="small">Small</Radio.Button>
<Radio.Button value="middle">Middle</Radio.Button>
<Radio.Button value="large">Large</Radio.Button>
</Radio.Group>
<Divider />
<ConfigProvider componentSize={componentSize}>
<div className="example">
<Input />
</div>
<div className="example">
<Select defaultValue="demo" options={[{ value: 'demo' }]} />
</div>
<div className="example">
<DatePicker />
</div>
<div className="example">
<Button>Button</Button>
</div>
<div className="example">
<Card title="Card">
<Table
columns={[
{ title: 'Name', dataIndex: 'name' },
{ title: 'Age', dataIndex: 'age' },
]}
dataSource={[
{
key: '1',
name: 'John Brown',
age: 32,
},
{
key: '2',
name: 'Jim Green',
age: 42,
},
{
key: '3',
name: 'Joe Black',
age: 32,
},
]}
/>
</Card>
</div>
</ConfigProvider>
</div>
);
};
ReactDOM.render(<FormSizeDemo />, mountNode);
API
参数 | 说明 | 类型 | 默认值 | 版本 |
---|---|---|---|---|
autoInsertSpaceInButton | 设置为 false 时,移除按钮中 2 个汉字之间的空格 | boolean | true | |
componentSize | 设置 antd 组件大小 | small | middle | large | - | |
csp | 设置 Content Security Policy 配置 | { nonce: string } | - | |
form | 设置 Form 组件的通用属性 | { validateMessages?: ValidateMessages } | - | |
renderEmpty | 自定义组件空状态。参考 空状态 | Function(componentName: string): ReactNode | - | |
getPopupContainer | 弹出框(Select, Tooltip, Menu 等等)渲染父节点,默认渲染到 body 上。 | Function(triggerNode) | () => document.body | |
locale | 语言包配置,语言包可到 antd/es/locale 目录下寻找 | object | - | |
prefixCls | 设置统一样式前缀。注意:这将不会应用由 antd 提供的默认样式 | string | ant | |
pageHeader | 统一设置 PageHeader 的 ghost,参考 PageHeader | { ghost: boolean } | 'true' | |
direction | 设置文本展示方向。 示例 | ltr | rtl | ltr |
FAQ
为什么我使用了 ConfigProvider locale,时间类组件的国际化还有问题?
请检查是否设置了 moment.locale('zh-cn')
,或者是否有两个版本的 moment 共存。
配置 getPopupContainer 导致 Modal 报错?
相关 issue:https://github.com/ant-design/ant-design/issues/19974
当如下全局设置 getPopupContainer
为触发节点的 parentNode 时,由于 Modal 的用法不存在 triggerNode
,这样会导致 triggerNode is undefined
的报错,需要增加一个判断条件。
<ConfigProvider
- getPopupContainer={triggerNode => triggerNode.parentNode}
+ getPopupContainer={node => {
+ if (node) {
+ return node.parentNode;
+ }
+ return document.body;
+ }}
>
<App />
</ConfigProvider>