块编辑器开发文档

💡 云策文档标注

概述

withFilters 是 Gutenberg 原生扩展性的一部分,作为一个 React 高阶组件,它允许通过外部 Hook 对组件进行过滤和定制。

关键要点

  • withFilters 是一个 React 高阶组件,用于包装组件以提供外部过滤能力。
  • 它接受一个字符串参数作为 hookName,通过 wp.hooks.addFilter 方法允许插件开发者自定义或覆盖组件。
  • 可以用于追加组件或覆盖 props,实现灵活的组件扩展。

代码示例

import { withFilters } from '@wordpress/components';
import { addFilter } from '@wordpress/hooks';

const MyComponent = ( { title } ) => <h1>{ title }</h1>;

const ComponentToAppend = () => <div>Appended component</div>;

function withComponentAppended( FilteredComponent ) {
    return ( props ) => (
        <>
            <FilteredComponent { ...props } />
            <ComponentToAppend />
        </>
    );
}

addFilter(
    'MyHookName',
    'my-plugin/with-component-appended',
    withComponentAppended
);

const MyComponentWithFilters = withFilters( 'MyHookName' )( MyComponent );

📄 原文内容

withFilters is a part of Native Gutenberg Extensibility. It is also a React higher-order component.

Wrapping a component with withFilters provides a filtering capability controlled externally by the hookName.

Usage

import { withFilters } from '@wordpress/components';
import { addFilter } from '@wordpress/hooks';

const MyComponent = ( { title } ) => <h1>{ title }</h1>;

const ComponentToAppend = () => <div>Appended component</div>;

function withComponentAppended( FilteredComponent ) {
    return ( props ) => (
        <>
            <FilteredComponent { ...props } />
            <ComponentToAppend />
        </>
    );
}

addFilter(
    'MyHookName',
    'my-plugin/with-component-appended',
    withComponentAppended
);

const MyComponentWithFilters = withFilters( 'MyHookName' )( MyComponent );

withFilters expects a string argument which provides a hook name. It returns a function which can then be used in composing your component. The hook name allows plugin developers to customize or completely override the component passed to this higher-order component using wp.hooks.addFilter method.

It is also possible to override props by implementing a higher-order component which works as follows:

import { withFilters } from '@wordpress/components';
import { addFilter } from '@wordpress/hooks';

const MyComponent = ( { hint, title } ) => (
    <>
        <h1>{ title }</h1>
        <p>{ hint }</p>
    </>
);

function withHintOverridden( FilteredComponent ) {
    return ( props ) => (
        <FilteredComponent { ...props } hint="Overridden hint" />
    );
}

addFilter( 'MyHookName', 'my-plugin/with-hint-overridden', withHintOverridden );

const MyComponentWithFilters = withFilters( 'MyHookName' )( MyComponent );