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

时间:2019-03-24 07:28:16

标签: javascript reactjs quill 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上找到了上述解决方案。但是它不起作用...

2 个答案:

答案 0 :(得分:1)

我相信您缺少对ReactQuill组件本身的引用。没有引用,您将无法访问其任何非特权方法(例如getLength())。您可以通过handleChange方法(https://github.com/zenoamaro/react-quill#props,即onChange属性的第4个参数)获得副本,但我建议您只需向ReactQuill组件添加一个单独的引用属性并使用。参见下面的示例,将其重写为功能组件(...自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} /> 
  ) 
}

答案 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}
            />
  }
}