如何在React-Quill中设置字符长度

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

如何在反应 - 羽毛笔中设置角色长度。在Docs中,getLength()将返回编辑器中字符的长度。

但我无法弄清楚如何实现它。

我的JSX

<ReactQuill theme='snow' 
                        onKeyDown={this.checkCharacterCount}
                        value={this.state.text}
                        onChange={this.handleChange}
                        modules={modules}
                        formats={formats}
                        //style={{height:'460px'}}
                         />
    // OnChange Handler
    handleChange = (value) =>  {
        this.setState({ text: value })
      }
      
      //Max VAlue checker
      checkCharacterCount = (event) => {
        if (this.getLength().length > 280 && event.key !== 'Backspace') {
            event.preventDefault();
        }
    }

我在GitHub上找到了上面的解决方案。但它不起作用......

javascript reactjs quill react-quill
1个回答
0
投票

以下应该工作:

class Editor extends React.Component {
  constructor (props) {
    super(props)
    this.handleChange = this.handleChange.bind(this)
    this.quillRef = null;      // Quill instance
    this.reactQuillRef = null;
    this.state = {editorHtml : ''};
  }
  componentDidMount() {
    this.attachQuillRefs()
  }

  componentDidUpdate() {
    this.attachQuillRefs()
  }

  attachQuillRefs = () => {
    if (typeof this.reactQuillRef.getEditor !== 'function') return;
    this.quillRef = this.reactQuillRef.getEditor();
  }
  handleChange (html) {
    var limit = 10;
    var quill = this.quillRef;
    quill.on('text-change', function (delta, old, source) {
      if (quill.getLength() > limit) {
       quill.deleteText(limit, quill.getLength());
      }
    });
    this.setState({ editorHtml: html });
  }


  render () {
    return  <ReactQuill 
            ref={(el) => { this.reactQuillRef = el }}
            theme="snow"
            onChange={this.handleChange}
            value={this.state.editorHtml}
            />
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.