首页 > 解决方案 > 如何在使用 reactQuill 组件时自定义 'image' 标签的宽高和样式?

问题描述

我正在研究小型反应项目。我将在 'toolbar' 中显示使用widthheight和一些样式(例如'display:inline''margin:auto' )指定的图像。

我就这样编写了我的项目以供参考。

.... ....

// before defining of the component
const WHITE_STYLE = ['margin', 'display', 'float'];

class ImageBlot extends BaseImage {
  static formats(domNode:any) {
    return ATTRIBUTES.reduce(function(formats:any, attribute:any) {
      if (domNode.hasAttribute(attribute)) {
          formats[attribute] = domNode.getAttribute(attribute);
      }
      return formats;
    }, {});
  }

  format(name:any, value:any) {
     if (ATTRIBUTES.indexOf(name) > -1) {
        if (value) {
            if (name === 'style') {
                value = this.sanitize_style(value);
            }
            this.domNode.setAttribute(name, value);
        } else {
            this.domNode.removeAttribute(name);
        }
     } else {
       super.format(name, value);
     }
  }

 sanitize_style(style:any) {
    let style_arr = style.split(";")
    let allow_style = "";
    style_arr.forEach((v:any, i:number) => {
        if (WHITE_STYLE.indexOf(v.trim().split(":")[0]) !== -1) {
            allow_style += v + ";"
        }
    })
    return allow_style;
  }
}

ImageBlot.blotName = 'imageBlot';
ImageBlot.className = 'image-blot';
ImageBlot.tagName = 'img';

Quill.register({ 'formats/imageBlot': ImageBlot });
.... ..... .....


.... ..... .....
//adding image tag dynamically...
if(this.ref && this.ref.current) {
        let index = this.state.index || 0;

        this.ref?.current.getEditor().insertEmbed(index, 'image', this.imageUrl, 'user');
        this.ref?.current.getEditor().formatText(index, 1, 'width', 100);
        this.ref?.current.getEditor().formatText(index, 1, 'height', 100);
        if( imageProperty.displayType === '2' && imageProperty.style === 'right')
            this.ref?.current.getEditor().formatText(index, 1, 'style', 'float:right');
        if( imageProperty.displayType === '2' && imageProperty.style === 'left')
            this.ref?.current.getEditor().formatText(index, 1, 'style', 'float:left');
        if( imageProperty.displayType === '1')
            this.ref?.current.getEditor().formatText(index, 1, 'style', 'display:block;margin:auto');
}


.... ....

不幸的是,结果只应用了宽度样式,没有别的。我该怎么做?谢谢!

标签: reactjsstyleswidthcustomizationquill

解决方案


推荐阅读