antDesign中的Message组件

1,187 阅读1分钟

官网用法

消息提示在项目中是比较常见的,比如登录成功,弹出消息提示,会提升用户的体验感。antDesign中有现成的消息提示组件 Message,官网中给出的例子是这样的:

import React from 'react'; 
import { Button, message } from 'antd'; 
const App: React.FC = () => { 
    const [messageApi, contextHolder] = message.useMessage(); 
    const info = () => { 
        messageApi.info('Hello, Ant Design!'); }; 
        return ( <> 
            {contextHolder} 
            <Button type="primary" onClick={info}> Display normal message </Button> </> 
            ); 
        }; export default App;

可以看见首先是使用了messageuseMessage方法,然后使用生成的messageApi中的 info方法来显示提示内容的。乍一看是挺方便的,后面还有例子可以实现不同类型的弹窗框,使用的是messageApi中的 open方法。一切都看来是那样的水到渠成,直到真正拿来用。。。

messageApi.open({ type: 'success', content: 'This is a success message', });

messageApi.open({ type: 'error', content: 'This is an error message', });

messageApi.open({ type: 'warning', content: 'This is a warning message', });

报错

将上述官网提供的方法拿到自己项目中去使用,你会发现并没有弹出预期的消息提示框,而且控制台很可能会报如下的错误(有咩有懂的小伙伴解释一下):

Warning: [antd: Message] You are calling notice in render which will break in React 18 concurren

解决办法

报错好像是跟钩子的使用有关,具体的我还没有去研究,但是我们可以使用官网下方提供的静态方法,就是直接使用message的方法,不用使用钩子(突然感觉又方便又不出错, 虽然官网是这样说:静态方法无法消费上下文,推荐优先使用 Hooks 版本【以后可以细致了解一下】)。

message.info('This is a normal message');

message.success('This is a successful message');

message.warning('This is a warning message');