块编辑器开发文档

💡 云策文档标注

概述

withNotices 是一个 React 高阶组件,用于为原始组件添加发布通知消息的功能。通过包装原始组件,它提供了 noticeOperations、noticeUI 和 noticeList 等额外属性。

关键要点

  • withNotices 是一个高阶组件,用于封装组件以支持通知功能。
  • noticeOperations 提供创建、移除通知的函数,如 createNotice、createErrorNotice、removeAllNotices 和 removeNotice。
  • noticeUI 是渲染的 NoticeList 组件,用于显示通知。
  • noticeList 是包含通知对象的数组,用于管理通知数据。

代码示例

import { withNotices, Button } from '@wordpress/components';

const MyComponentWithNotices = withNotices(
    ( { noticeOperations, noticeUI } ) => {
        const addError = () =>
            noticeOperations.createErrorNotice( 'Error message' );
        return (
            <div>
                { noticeUI }
                <Button variant="secondary" onClick={ addError }>
                    Add error
                </Button>
            </div>
        );
    }
);

📄 原文内容

withNotices is a React higher-order component used typically in adding the ability to post notice messages within the original component.

Wrapping the original component with withNotices encapsulates the component with the additional props noticeOperations, noticeUI, and noticeList.

noticeOperations
Contains a number of useful functions to add notices to your site.

# createNotice
Function passed down as a prop that adds a new notice.

Parameters

  • notice object: Notice to add.

# createErrorNotice
Function passed as a prop that adds a new error notice.

Parameters

  • msg string: Error message of the notice.

# removeAllNotices
Function that removes all notices.

# removeNotice
Function that removes notice by ID.

Parameters

  • id string: ID of notice to remove.

#noticeUi
The rendered NoticeList.

#noticeList
The array of notice objects to be displayed.

Usage

import { withNotices, Button } from '@wordpress/components';

const MyComponentWithNotices = withNotices(
    ( { noticeOperations, noticeUI } ) => {
        const addError = () =>
            noticeOperations.createErrorNotice( 'Error message' );
        return (
            <div>
                { noticeUI }
                <Button variant="secondary" onClick={ addError }>
                    Add error
                </Button>
            </div>
        );
    }
);