2020-02-03 13:00:35 +08:00
|
|
|
---
|
|
|
|
order: 12
|
|
|
|
title:
|
|
|
|
zh-CN: 使用 hooks 获得上下文
|
|
|
|
en-US: Use hooks to get context
|
|
|
|
---
|
|
|
|
|
|
|
|
## zh-CN
|
|
|
|
|
|
|
|
通过 `Modal.useModal` 创建支持读取 context 的 `contextHolder`。
|
|
|
|
|
|
|
|
## en-US
|
|
|
|
|
|
|
|
Use `Modal.useModal` to get `contextHolder` with context accessible issue.
|
|
|
|
|
2022-05-19 09:46:26 +08:00
|
|
|
```tsx
|
2022-05-21 22:14:15 +08:00
|
|
|
import { Button, Modal, Space } from 'antd';
|
2022-05-19 09:46:26 +08:00
|
|
|
import React, { createContext } from 'react';
|
2020-02-03 13:00:35 +08:00
|
|
|
|
2022-05-19 09:46:26 +08:00
|
|
|
const ReachableContext = createContext<string | null>(null);
|
|
|
|
const UnreachableContext = createContext<string | null>(null);
|
2020-02-03 13:00:35 +08:00
|
|
|
|
|
|
|
const config = {
|
|
|
|
title: 'Use Hook!',
|
|
|
|
content: (
|
2020-07-16 13:46:57 +08:00
|
|
|
<>
|
2020-02-03 13:00:35 +08:00
|
|
|
<ReachableContext.Consumer>{name => `Reachable: ${name}!`}</ReachableContext.Consumer>
|
|
|
|
<br />
|
|
|
|
<UnreachableContext.Consumer>{name => `Unreachable: ${name}!`}</UnreachableContext.Consumer>
|
2020-07-16 13:46:57 +08:00
|
|
|
</>
|
2020-02-03 13:00:35 +08:00
|
|
|
),
|
|
|
|
};
|
|
|
|
|
2022-05-19 09:46:26 +08:00
|
|
|
const App: React.FC = () => {
|
2020-02-03 13:00:35 +08:00
|
|
|
const [modal, contextHolder] = Modal.useModal();
|
|
|
|
|
|
|
|
return (
|
|
|
|
<ReachableContext.Provider value="Light">
|
2020-04-30 21:04:19 +08:00
|
|
|
<Space>
|
|
|
|
<Button
|
|
|
|
onClick={() => {
|
|
|
|
modal.confirm(config);
|
|
|
|
}}
|
|
|
|
>
|
|
|
|
Confirm
|
|
|
|
</Button>
|
|
|
|
<Button
|
|
|
|
onClick={() => {
|
|
|
|
modal.warning(config);
|
|
|
|
}}
|
|
|
|
>
|
|
|
|
Warning
|
|
|
|
</Button>
|
|
|
|
<Button
|
|
|
|
onClick={() => {
|
|
|
|
modal.info(config);
|
|
|
|
}}
|
|
|
|
>
|
|
|
|
Info
|
|
|
|
</Button>
|
|
|
|
<Button
|
|
|
|
onClick={() => {
|
|
|
|
modal.error(config);
|
|
|
|
}}
|
|
|
|
>
|
|
|
|
Error
|
|
|
|
</Button>
|
|
|
|
</Space>
|
2020-02-03 13:00:35 +08:00
|
|
|
{/* `contextHolder` should always under the context you want to access */}
|
|
|
|
{contextHolder}
|
|
|
|
|
|
|
|
{/* Can not access this context since `contextHolder` is not in it */}
|
|
|
|
<UnreachableContext.Provider value="Bamboo" />
|
|
|
|
</ReachableContext.Provider>
|
|
|
|
);
|
|
|
|
};
|
|
|
|
|
2022-04-15 16:20:56 +08:00
|
|
|
export default App;
|
2020-02-03 13:00:35 +08:00
|
|
|
```
|