admin管理员组

文章数量:1122846

I want to get the selected block (an inner block) every time a new block is selected.

I am trying the following:

edit() {
  const selectedBlock = wp.data.select( 'core/block-editor' ).getSelectedBlock();
  
  useEffect( () => {
    console.log( selectedBlock );
  }, [ selectedBlock ] );
})

The selected block is returned only when the block renders. Nothing happens when I select a new inner block. It works only when I click out of the parent block, then click again an inner block.

I want to get the selected block (an inner block) every time a new block is selected.

I am trying the following:

edit() {
  const selectedBlock = wp.data.select( 'core/block-editor' ).getSelectedBlock();
  
  useEffect( () => {
    console.log( selectedBlock );
  }, [ selectedBlock ] );
})

The selected block is returned only when the block renders. Nothing happens when I select a new inner block. It works only when I click out of the parent block, then click again an inner block.

Share Improve this question asked Jul 19, 2022 at 22:15 CyberJCyberJ 4375 silver badges19 bronze badges 1
  • Does this answer your question? How do I access site and block editor state data and use `useSelect()` or `withSelect()` to bind it to my components? – bosco Commented Jul 20, 2022 at 5:33
Add a comment  | 

1 Answer 1

Reset to default 0

In short, use the useSelect() hook or the withSelect() HOC utility from @wordpress/data to create a subscription to selected value. Either will trigger a render whenever the selected value changes in state:

import { useSelect } from '@wordpress/data';

edit() {
  const selectedBlock = useSelect(
    ( select ) => select( 'core/block-editor' ).getSelectedBlock()
  );

  useEffect( () => {
    console.log( selectedBlock );
  }, [ selectedBlock ] );
}

本文标签: Get selected block every time a new block is selected in Gutenberg