简体   繁体   English

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

[英]How to Set a character length in React-Quill

How can I set Character Length in react-quill.如何在 react-quill 中设置字符长度。 In Docs it has been given that getLength() will return the length of the character in editor..在文档中已经给出 getLength() 将返回编辑器中字符的长度。

But I am Unable to figure out How to implement it.但我无法弄清楚如何实施它。

My JSX我的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(); } }

The Above solution i found on GitHub. But its not working...我在 GitHub 上找到的上述解决方案。但它不起作用...

I believe you are missing a reference to the ReactQuill component itself.我相信您缺少对ReactQuill组件本身的引用。 Without the reference you will not get access to any of its unprivileged methods (eg getLength() ).如果没有引用,您将无法访问其任何非特权方法(例如getLength() )。 You could get a copy via your handleChange method ( https://github.com/zenoamaro/react-quill#props , ie 4th argument on the onChange prop) but I would recommend you simply add a separate ref prop to the ReactQuill component and use that.您可以通过handleChange方法( https://github.com/zenoamaro/react-quill#props ,即 onChange 道具上的第 4 个参数)获取副本,但我建议您只需向ReactQuill组件添加一个单独的 ref 道具,然后用那个。 See below an example re-written as a functional component (...since its 2020 already):请参阅下面一个重写为功能组件的示例(...自 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} /> 
  ) 
}

Following should work:以下应该工作:

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

I don't have a "proper" solution but more a workaround with tiny-emitter that works also with copy-paste situations.我没有“合适的”解决方案,但更多的是使用tiny-emitter的解决方法,它也适用于复制粘贴情况。

  • First, we had to create a CopyPaste class extends from clipboard module.首先,我们必须创建一个CopyPaste class extends from clipboard模块。 In that class, we put an emitter and pass the quill instance into parameter.在那个 class 中,我们放置了一个发射器并将quill实例传递给参数。

 const Emitter = require('tiny-emitter/instance'); const { Quill } = typeof window === 'object'? require('react-quill'): () => false; const Delta = typeof window === 'object'? require('quill-delta'): null; const Clipboard = typeof window === 'object'? Quill.import('modules/clipboard'): null; export class CopyPasteQuill extends Clipboard { onPaste(e) { e.preventDefault(); const range = this.quill.getSelection(); const text = e.clipboardData.getData('text/plain'); const delta = new Delta().retain(range.index).delete(range.length).insert(text); const index = text.length + range.index; const length = 0; this.quill.updateContents(delta, 'silent'); this.quill.setSelection(index, length, 'silent'); Emitter.emit('reactQuill::paste', this.quill); } }

  • Second, we have a normalize component ReactQuillInput to handle every cases.其次,我们有一个标准化组件ReactQuillInput来处理所有情况。 The only warning is linked to values that are passed to this component.唯一的警告链接到传递给该组件的值。 You can't give him props directly, you have to store them in a state before. props不能直接给他,得先存到一个state里面。

 import React, { useState } from 'react'; import ReactQuillInput from '@components/atoms/reactQuillInput/ReactQuillInput'; const component = props => { const { text } = props; const [quillValueState, setQuillValueState] = useState( text? text: '' ); const onChange = html => { setQuillValueState(html); }; const reactQuillMaxLength = 300; return ( <Container> <ReactQuillInput theme="bubble" defaultValue={captionState} value={captionState} onChangeText={onChange} placeholder={'Type your text...'} maxLength={reactQuillMaxLength} /> </Container> ) } export default component;

 import React, { useState } from 'react'; import PropTypes from 'prop-types'; import ReactQuill, { Quill } from 'react-quill'; import Emitter from 'tiny-emitter/instance'; import { CopyPasteQuill } from '@src/utils/copyPasteQuill'; import 'react-quill/dist/quill.snow.css'; require('medium-editor/dist/css/medium-editor.css'); require('../../../styles/content_editor.css'); require('../../../styles/quill.bubble.css'); const ReactQuillInput = props => { const { onChangeText, maxLength } = props; const [quillState, setQuillState] = useState({}); const [isMountedState, setIsMontedState] = useState(false); if (typeof window === 'object' && isMountedState) { Quill.register('modules/clipboard', CopyPasteQuill, true); } const setQuill = ref => { if (;ref || ref === null) return. if (typeof ref;getEditor.== 'function') return; setQuillState(ref;getEditor()); setIsMontedState(true); }. const handleChange = html => { if (,isMountedState) return. if (maxLength) { quillState.on('text-change', () => { if (quillState.getLength() > maxLength) { quillState;deleteText(maxLength; quillState;getLength()); } }). } onChangeText(html): }: Emitter,on('reactQuill..paste', _quill => { if (maxLength) { if (_quill.getLength() > maxLength) { _quill;deleteText(maxLength; _quill;getLength()). } } }). return ( <ReactQuill ref={el => { setQuill(el). }} {;;;props} onChange={handleChange} /> ). }: export default ReactQuillInput. ReactQuillInput,propTypes = { onChangeText: PropTypes.func, maxLength; PropTypes.number: }, ReactQuillInput;defaultProps = { onChangeText: () => {}, };

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM