如何在React-quill中显示字符计数器。

问题描述 投票:0回答:1

我想在我的React Quill上添加一个字符计数器。目前我有一个950的字符限制器.问题是用户必须意识到字符数不能超过950,因此字符计数器我已经尝试添加了 getLength() 但却给了我一个错误。这是我的代码。

attachQuillRefs = () => {
    if (typeof this.reactQuillRef.getEditor !== "function") return;
    this.quillRef = this.reactQuillRef.getEditor();
  };

  //Handles changes to description field
  handleDetailChange(value) {
    var limit = 950;
    var quill = this.quillRef;
    quill.on("text-change", function (delta, old, source) {
      if (quill.getLength() > limit) {
        quill.deleteText(limit, quill.getLength());
      }
    });
    this.setState({
      detail: value,
    });
  }

在Render:

<ReactQuill
     ref={(el) => {
        this.reactQuillRef = el;
     }}
     onChange={this.handleDetailChange}
        value={this.state.detail || ""}
     >
     <p>{this.reactQuillRef.getLength() + "/950"}</p>
</ReactQuill>
reactjs character limit charactercount react-quill
1个回答
1
投票

1)创建一个自定义模块,并将其注册为qill,如下图所示。

    class Counter {
    constructor(quill, options) {
      this.quill = quill;
      this.options = options;
      this.container = document.querySelector(options.container);
      quill.on('text-change', this.update.bind(this));
      this.update();  // Account for initial contents
    }

    calculate() {
      let text = this.quill.getText().trim();
      if (this.options.unit === 'word') {
        text = text.trim();
        // Splitting empty text returns a non-empty array
        return text.length > 0 ? text.split(/\s+/).length : 0;
      } else {
        return text.length;
      }
    }

    update() {
      var length = this.calculate();
      var label = this.options.unit;
      if (length !== 1) {
        label += 's';
      }
      this.container.innerText = length + ' ' + label;
    }
  }
 Quill.register('modules/counter', Counter);

2)然后添加以下代码到模块中,如图所示。

counter: {
    container: '#counter',
    unit: 'character'
  }

enter image description here

3)现在你可以在quilleditor标签下添加一个新的div标签,id为counter。

<ReactQuill
     ref={(el) => {
        this.reactQuillRef = el;
     }}
     onChange={this.handleDetailChange}
        value={this.state.detail || ""}
     >
     <p>{this.reactQuillRef.getLength() + "/950"}</p>
</ReactQuill>
<div id="counter">0</div>

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.