2020-02-07 17:55:27 +08:00
---
2022-05-11 14:26:18 +08:00
order: -1
2020-02-07 17:55:27 +08:00
title:
2022-05-11 14:26:18 +08:00
zh-CN: Hooks 调用(推荐)
en-US: Hooks usage (recommended)
2020-02-07 17:55:27 +08:00
---
## zh-CN
2022-05-11 14:26:18 +08:00
通过 `notification.useNotification` 创建支持读取 context 的 `contextHolder` 。请注意,我们推荐通过顶层注册的方式代替 `message` 静态方法,因为静态方法无法消费上下文,因而 ConfigProvider 的数据也不会生效。
2020-02-07 17:55:27 +08:00
## en-US
2022-05-11 14:26:18 +08:00
Use `notification.useNotification` to get `contextHolder` with context accessible issue. Please note that, we recommend to use top level registration instead of `notification` static method, because static method cannot consume context, and ConfigProvider data will not work.
2020-02-07 17:55:27 +08:00
2022-05-19 09:46:26 +08:00
```tsx
2020-02-07 17:55:27 +08:00
import {
RadiusBottomleftOutlined,
RadiusBottomrightOutlined,
2022-05-21 22:14:15 +08:00
RadiusUpleftOutlined,
RadiusUprightOutlined,
2020-02-07 17:55:27 +08:00
} from '@ant-design/icons';
2022-05-21 22:14:15 +08:00
import { Button, Divider, notification, Space } from 'antd';
2022-07-05 22:38:57 +08:00
import type { NotificationPlacement } from 'antd/es/notification/interface';
2022-05-21 22:14:15 +08:00
import React from 'react';
2020-02-07 17:55:27 +08:00
const Context = React.createContext({ name: 'Default' });
2022-05-19 09:46:26 +08:00
const App: React.FC = () => {
2020-02-07 17:55:27 +08:00
const [api, contextHolder] = notification.useNotification();
2022-05-19 09:46:26 +08:00
const openNotification = (placement: NotificationPlacement) => {
2020-02-07 17:55:27 +08:00
api.info({
message: `Notification ${placement}` ,
description: < Context.Consumer > {({ name }) => `Hello, ${name}!` }</ Context.Consumer > ,
placement,
});
};
return (
< Context.Provider value = {{ name: ' Ant Design ' } } >
{contextHolder}
2020-04-30 21:04:19 +08:00
< Space >
< Button type = "primary" onClick = {() = > openNotification('topLeft')}>
< RadiusUpleftOutlined / >
topLeft
< / Button >
< Button type = "primary" onClick = {() = > openNotification('topRight')}>
< RadiusUprightOutlined / >
topRight
< / Button >
< / Space >
2020-02-07 17:55:27 +08:00
< Divider / >
2020-04-30 21:04:19 +08:00
< Space >
< Button type = "primary" onClick = {() = > openNotification('bottomLeft')}>
< RadiusBottomleftOutlined / >
bottomLeft
< / Button >
< Button type = "primary" onClick = {() = > openNotification('bottomRight')}>
< RadiusBottomrightOutlined / >
bottomRight
< / Button >
< / Space >
2020-02-07 17:55:27 +08:00
< / Context.Provider >
);
};
2022-05-19 09:46:26 +08:00
export default App;
2020-02-07 17:55:27 +08:00
```