【问题标题】:Gutenberg custom block with responsive images带有响应式图像的古腾堡自定义块
【发布时间】:2019-01-23 22:58:23
【问题描述】:

我按照本教程学习了如何构建自定义 WordPress Gutenberg 块:https://neliosoftware.com/blog/how-to-create-your-first-block-for-gutenberg/

第一个块很好,但我想在这个块中使用自定义图像大小。此图像大小也应该是响应式的,这意味着应该在前端添加其他图像大小的 srcset 属性。

我在互联网上搜索了很长时间,但没有找到任何东西。使用来自 wordpress 的标准图像块或画廊块调整大小的图像,但对我来说,整个代码太复杂而无法遵循,因为我还不习惯古腾堡的编码方式......

是否有任何现有指南或代码示例说明如何实现这一目标?

最好的 卢卡斯

【问题讨论】:

  • 我来到这里是为了达到同样的目的。我会更新一个答案。我很接近(我希望)。

标签: wordpress srcset wordpress-gutenberg gutenberg-blocks


【解决方案1】:

我在this gutenberg github issue 的帮助下找到了解决方案。简单的答案是,wordpress (php) 使用wp_make_content_images_responsive-函数自动响应类名wp-image-<id> 转换所有图像。

也就是说,您需要做的就是在save 函数中将上述类名添加到您的图像中。

应用于您提到的示例,它将类似于以下内容:

save: function( props ) {
  var attributes = props.attributes;
  var alignment = props.attributes.alignment;
  var imageClass = 'wp-image-' + props.attributes.mediaId;

  return (
    el( 'div', { className: props.className },
      attributes.mediaURL &&
      el( 'div', { className: 'nelio-testimonial-image', style: { backgroundImage: 'url('+attributes.mediaURL+')' } },
        el( 'img', { src: attributes.mediaURL, class: imageClass } ),
      ),
      el( 'div', { className: 'nelio-testimonial-content', style: { textAlign: attributes.alignment } },
        attributes.testimonial && el( 'p', {}, attributes.testimonial ),
        el( 'p', { className: 'nelio-testimonial-name' }, attributes.name ),
        attributes.position && el( 'p', { className: 'nelio-testimonial-position' }, attributes.position )
      )
    )
  );
},

【讨论】:

  • 我一直在到处寻找这样的东西 - 谢谢!
猜你喜欢
  • 2019-06-26
  • 2021-06-22
  • 2022-10-20
  • 2021-10-08
  • 2019-08-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多