最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

How can I programmatically select a Gutenberg block?

programmeradmin0浏览0评论

I'm creating a Gutenberg block that contains a live map (like Google Maps or OpenStreetMaps). The issue I run into is that clicking on the map doesn't select the block, so that the toolbar and inspector controls never show up. I'm able to capture the click, but I'm not sure what command I should call to select the block that contains the map the user clicked on. I tried looking through the docs but couldn't find an API for this. I also tried calling click() on several divs that wrap the block, but no luck.

I also noticed that other blocks that have to deal with this kind of dynamic content use a div that overlays on top of the dynamic content to sidestep this issue. I'm trying to not use this kind of method to give the user a very dynamic editing experience.

The registerBlockType edit prop returns this:

   wp.element.createElement('div', {className: 'map-block-wrapper'},
      wp.element.createElement(MapBlock.default, createOptions)
   )

You can see that this uses a MapBlock React component. This is the custom component I wrote to display the dynamic map. Instead of posting the entire file I'll just put the relevant parts here.

MapBlock.js:

constructor(props) {
    super(props)
    this.el = React.createRef()
    //Load third party mapping library (like google, etc)
    this.map = new google.maps.Map(this.el, mapOptions);
}

render() {
  return (<div className="map" ref={this.el} style={{height: '350px'}}  />)
}

This displays the map on the editor, but since you can zoom and pan the map with the mouse, the mouse events are captured and they don't bubble to the editor to show the toolbar and the block inspector.

发布评论

评论列表(0)

  1. 暂无评论