消息组件用于显示内联消息。
import { Messages } from 'primereact/messages';
通过调用组件的 ref 提供的 show 方法来显示消息。单个消息由消息接口指定,该接口定义了各种属性,例如 severity、summary 和 详细信息
<Messages ref={msgs} />
severity 选项指定消息的类型。
msgs.current.show([
{sticky: true, severity: 'info', summary: 'Info', detail: 'Message Content', closable: false},
{sticky: true, severity: 'success', summary: 'Success', detail: 'Message Content', closable: false},
{sticky: true, severity: 'warn', summary: 'Warning', detail: 'Message Content', closable: false},
{sticky: true, severity: 'error', summary: 'Error', detail: 'Message Content', closable: false},
{sticky: true, severity: 'secondary', summary: 'Secondary', detail: 'Message Content', closable: false},
{sticky: true, severity: 'contrast', summary: 'Contrast', detail: 'Message Content', closable: false}
]);
通过将数组传递给 show 方法来显示多条消息。
<Button type="button" onClick={addMessages} label="Show" className="mr-2" />
<Button type="button" onClick={clearMessages} label="Clear" className="p-button-secondary" />
<Messages ref={msgs} />
默认情况下,消息会显示关闭图标,closable 选项用于控制此行为。
msgs.current.show([
{ sticky: true, severity: 'success', summary: 'Success', detail: 'Message is closable'},
{ sticky: true, severity: 'info', summary: 'Info', detail: 'Message is not closable', closable: false}
]);
消息在 life 选项定义的 3000 毫秒后消失,将 sticky 选项设置为显示不会自动隐藏的消息。
msgs.current.show([
{ sticky: true, life: 1000, severity: 'success', summary: 'Success', detail: 'Message Content', closable: false },
{ sticky: true, life: 2000, severity: 'info', summary: 'Info', detail: 'Message Content', closable: false },
{ sticky: true, life: 3000, severity: 'warn', summary: 'Warning', detail: 'Message Content', closable: false },
{ sticky: true, life: 4000, severity: 'error', summary: 'Error', detail: 'Message Content', closable: false }
]);
可以通过简单地使用 icon 或 content 选项来创建具有自定义图标的消息。
msgs.current.show([
{ sticky: true, severity: 'info', icon: 'pi pi-send', detail: 'Info message' },
{
severity: 'success',
sticky: true,
content: (
<React.Fragment>
<img alt="logo" src="https://primefaces.org/cdn/primereact/images/avatar/amyelsner.png" width="32" />
<div className="ml-2">How may I help you?</div>
</React.Fragment>
)
}
]);
使用 content 选项定义消息内的自定义内容。
msgs.current.show({
severity: 'info',
sticky: true,
content: (
<React.Fragment>
<img alt="logo" src="/images/logo.png" width="32" />
<div className="ml-2">Always bet on Prime.</div>
</React.Fragment>
)
});
消息组件使用 alert 角色,该角色隐式地将 aria-live 定义为“assertive”,将 aria-atomic 定义为“true”。由于任何属性都传递给根元素,因此属性如 aria-labelledby 和 aria-label 也可以选择使用。
关闭元素是一个 button,其 aria-label 默认引用 locale API 的 aria.close 属性,你可以使用 closeButtonProps 自定义元素并覆盖默认的 aria-label。
按键 | 功能 |
---|---|
回车键 | 关闭消息。 |
空格键 | 关闭消息。 |