Как получить доступ к ReactQuill Ref при использовании динамического импорта c в Next JS? - PullRequest
0 голосов
/ 28 февраля 2020

Я столкнулся с забавной проблемой. Я использую Next JS для его рендеринга на стороне сервера и использую ReactQuill в качестве редактора форматированного текста. Чтобы обойти ReactQuill t ie в DOM, я его динамически импортирую. Однако это представляет другую проблему, заключающуюся в том, что когда я пытаюсь прикрепить ссылку к компоненту ReactQuill, он обрабатывается как загружаемый компонент вместо компонента ReactQuill. Мне нужна ссылка для того, чтобы настроить обработку изображений при загрузке в текстовый редактор. Сейчас ссылка возвращает current: null вместо функции, которую я могу использовать .getEditor () для настройки обработки изображений.

У кого-нибудь есть мысли о том, как я могу решить эту проблему? Я попытался переадресовать, но он все еще применяет ссылки к загружаемому компоненту, а не к React-Quill. Вот снимок моего кода.

const ReactQuill = dynamic(import('react-quill'), { ssr: false, loading: () => <p>Loading ...</p> }
);

const ForwardedRefComponent = React.forwardRef((props, ref) => {return (
    <ReactQuill {...props} forwardedRef={(el) => {ref = el;}} />
)})

class Create extends Component {
    constructor() {
        super();
        this.reactQuillRef = React.createRef();
    }

    imageHandler = () => {
         console.log(this.reactQuillRef); //this returns current:null, can't use getEditor() on it.
    }
    render() {
    const modules = {
      toolbar: {
          container:  [[{ 'header': [ 2, 3, false] }],
            ['bold', 'italic', 'underline', 'strike'],
            [{ 'list': 'ordered'}, { 'list': 'bullet' }],
            [{ 'script': 'sub'}, { 'script': 'super' }],
            ['link', 'image'],
            [{ 'indent': '-1'}, { 'indent': '+1' }],    
            [{ 'align': [] }],
            ['blockquote', 'code-block'],],
          handlers: {
             'image': this.imageHandler
          }
        }
     };
         return(
             <ForwardedRefComponent 
                value={this.state.text}
                onChange={this.handleChange}
                modules={modules}
                ref={this.reactQuillRef}/> //this.reactQuillRef is returning current:null instead of the ReactQuill function for me to use .getEditor() on
         )
    }
}

const mapStateToProps = state => ({
    tutorial: state.tutorial,
});

export default connect(
    mapStateToProps, {createTutorial}
)(Create);

1 Ответ

0 голосов
/ 12 марта 2020

Используйте onChange и передайте все аргументы, вот один пример для использования editor.get HTML ()


import React, { Component } from 'react'
import dynamic from 'next/dynamic'
import { render } from 'react-dom'

const QuillNoSSRWrapper = dynamic(import('react-quill'), {
  ssr: false,
  loading: () => <p>Loading ...</p>,
})

const modules = {
  toolbar: [
    [{ header: '1' }, { header: '2' }, { font: [] }],
    [{ size: [] }],
    ['bold', 'italic', 'underline', 'strike', 'blockquote'],
    [
      { list: 'ordered' },
      { list: 'bullet' },
      { indent: '-1' },
      { indent: '+1' },
    ],
    ['link', 'image', 'video'],
    ['clean'],
  ],
  clipboard: {
    // toggle to add extra line breaks when pasting HTML:
    matchVisual: false,
  },
}
/*
 * Quill editor formats
 * See https://quilljs.com/docs/formats/
 */
const formats = [
  'header',
  'font',
  'size',
  'bold',
  'italic',
  'underline',
  'strike',
  'blockquote',
  'list',
  'bullet',
  'indent',
  'link',
  'image',
  'video',
]

class BlogEditor extends Component {
  constructor(props) {
    super(props)
    this.state = { value: null } // You can also pass a Quill Delta here
    this.handleChange = this.handleChange.bind(this)
    this.editor = React.createRef()
  }

  handleChange = (content, delta, source, editor) => {
    this.setState({ value: editor.getHTML() })
  }

  render() {
    return (
      <>
        <div dangerouslySetInnerHTML={{ __html: this.state.value }} />
        <QuillNoSSRWrapper ref={this.editor} onChange={this.handleChange} modules={modules} formats={formats} theme="snow" />
        <QuillNoSSRWrapper value={this.state.value} modules={modules} formats={formats} theme="snow" />
      </>
    )
  }
}
export default BlogEditor
...