3

如何在 react-quill 中设置字符长度。在 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 上找到的上述解决方案。但它不起作用...

4

2 回答 2

3

以下应该工作:

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}
            />
  }
}
于 2019-03-29T14:14:26.347 回答
3

我相信您缺少对ReactQuill组件本身的引用。如果没有引用,您将无法访问其任何非特权方法(例如getLength())。handleChange您可以通过您的方法获取副本( https://github.com/zenomaro/react-quill#props,即 onChange 道具上的第四个参数),但我建议您只需向ReactQuill组件添加一个单独的 ref 道具并使用它. 请参阅下面一个重写为功能组件的示例(......自 2020 年以来):

export const Editor = () => {
  const [value, setValue] = React.useState(null);
  const reactQuillRef = React.useRef();

  const handleChange = (value) => setValue(value);

  const checkCharacterCount = (event) => {
    const unprivilegedEditor = reactQuillRef.current.unprivilegedEditor;
    if (unprivilegedEditor.getLength() > 280 && event.key !== 'Backspace')
      event.preventDefault();
  };

  return (
    <ReactQuill theme='snow' 
      onKeyDown={checkCharacterCount}
      ref={reactQuillRef}
      value={this.state.text}
      onChange={this.handleChange}
      modules={modules}
      formats={formats} /> 
  ) 
}
于 2020-06-17T10:54:48.117 回答