Site icon May's Notes

Antd message 警告 Static function can not consume context like dynamic theme

antd logo

錯誤訊息

 warning: [antd: message] Static function can not consume context like dynamic theme. Please use 'App' component instead.

解決方法

官方推薦使用 App 組件解決。

在 ConfigProvider 中使用 App 組件包裹其他組件

<ConfigProvider theme={{ ... }}>
  <App>
    ...
  </App>
</ConfigProvider>

大致像這樣

import React from 'react';
import { App } from 'antd';

const MyPage: React.FC = () => {
  const { message, notification, modal } = App.useApp();
  message.success('Good!');
  notification.info({ message: 'Good' });
  modal.warning({ title: 'Good' });
  // ....
  // other message, notification, modal static function
  return <div>Hello word</div>;
};

const MyApp: React.FC = () => (
  <ConfigProvider theme={{ ... }}>
    <App>
      <MyPage />
    </App>
  </ConfigProvider>
);

export default MyApp;
Exit mobile version