本文档介绍了 WordPress 自定义小工具功能中的核心选择器和操作,包括 isInserterOpened 选择器和 setIsInserterOpened 操作,用于管理插入器的状态。
import { store as customizeWidgetsStore } from '@wordpress/customize-widgets';
import { __ } from '@wordpress/i18n';
import { useSelect } from '@wordpress/data';
const ExampleComponent = () => {
const { isInserterOpened } = useSelect(
( select ) => select( customizeWidgetsStore ),
[]
);
return isInserterOpened()
? __( 'Inserter is open' )
: __( 'Inserter is closed.' );
};import { useState } from 'react';
import { store as customizeWidgetsStore } from '@wordpress/customize-widgets';
import { __ } from '@wordpress/i18n';
import { useDispatch } from '@wordpress/data';
import { Button } from '@wordpress/components';
const ExampleComponent = () => {
const { setIsInserterOpened } = useDispatch( customizeWidgetsStore );
const [ isOpen, setIsOpen ] = useState( false );
return (
<Button
onClick={ () => {
setIsInserterOpened( ! isOpen );
setIsOpen( ! isOpen );
} }
>
{ __( 'Open/close inserter' ) }
</Button>
);
}; Namespace: core/customize-widgets.
Returns true if the inserter is opened.
Usage
import { store as customizeWidgetsStore } from '@wordpress/customize-widgets';
import { __ } from '@wordpress/i18n';
import { useSelect } from '@wordpress/data';
const ExampleComponent = () => {
const { isInserterOpened } = useSelect(
( select ) => select( customizeWidgetsStore ),
[]
);
return isInserterOpened()
? __( 'Inserter is open' )
: __( 'Inserter is closed.' );
};
Parameters
Object: Global application state.Returns
boolean: Whether the inserter is opened.Returns an action object used to open/close the inserter.
Usage
import { useState } from 'react';
import { store as customizeWidgetsStore } from '@wordpress/customize-widgets';
import { __ } from '@wordpress/i18n';
import { useDispatch } from '@wordpress/data';
import { Button } from '@wordpress/components';
const ExampleComponent = () => {
const { setIsInserterOpened } = useDispatch( customizeWidgetsStore );
const [ isOpen, setIsOpen ] = useState( false );
return (
<Button
onClick={ () => {
setIsInserterOpened( ! isOpen );
setIsOpen( ! isOpen );
} }
>
{ __( 'Open/close inserter' ) }
</Button>
);
};
Parameters
boolean|Object: Whether the inserter should be opened (true) or closed (false). To specify an insertion point, use an object.string: The root client ID to insert at.number: The index to insert at.Returns
Object: Action object.