(CKEditor) Окно не определено ReactJS при реализации - PullRequest
0 голосов
/ 18 октября 2019

Я хотел бы внедрить CKEditor в свой реактивный проект. Тем не менее, я получил ошибку при попытке загрузить его. Я следил за всей официальной документацией. Я понятия не имею, почему, в любом случае, вот мой код

import React from 'react';

class MyEditor extends React.Component {
    state = {loading: true};

    componentDidMount() {
        this.CKEditor = require("@ckeditor/ckeditor5-react");
        this.ClassicEditor = require("@ckeditor/ckeditor5-build-classic");
        this.setState({ loading: false }); 
    }

    render() {
        return ({this.CKEditor && (<this.CKEditor editor={this.ClassicEditor} data="<p>Hello from CKEditor 5!</p>"
                onInit={ editor => {
                    // You can store the "editor" and use when it is needed.
                    console.log( 'Editor is ready to use!', editor );
                } }
                onChange={ ( event, editor ) => {
                    const data = editor.getData();
                    console.log( { event, editor, data } );
                } }/>)})
    }
}

export default MyEditor;

Я получаю следующую ошибку

ReferenceError: окно не определено в Object. (/ Users / bobbyjulian / Рабочий стол / проект / test / node_modules / ckeditor / ckeditor5-реагировать / dist / ckeditor.js: 5: 244 Module._compile internal / modules / cjs / loader.js: 778: 30 Module._extensions .. js internal / modules / cjs / loader.js: 789: 10 Module.load внутренний / modules / cjs / loader.js: 653: 32 tryModuleLoad внутренний / modules / cjs / loader.js: 593: 12

Я очень ценю любой ответ. Спасибо.

Ответы [ 2 ]

0 голосов
/ 27 октября 2019

Вот рабочий пример с NextJS и React Hooks. Мы можем воспользоваться useRef, чтобы удержать экземпляры редактора.

import React, { useState, useEffect, useRef } from 'react'

export default function MyEditor () {
  const editorRef = useRef()
  const [editorLoaded, setEditorLoaded] = useState(false)
  const { CKEditor, ClassicEditor } = editorRef.current || {}

  useEffect(() => {
    editorRef.current = {
      CKEditor: require('@ckeditor/ckeditor5-react'),
      ClassicEditor: require('@ckeditor/ckeditor5-build-classic')
    }
    setEditorLoaded(true)
  }, [])

  return editorLoaded ? (
    <CKEditor
      editor={ClassicEditor}
      data='<p>Hello from CKEditor 5!</p>'
      onInit={editor => {
        // You can store the "editor" and use when it is needed.
        console.log('Editor is ready to use!', editor)
      }}
      onChange={(event, editor) => {
        const data = editor.getData()
        console.log({ event, editor, data })
      }}
    />
  ) : (
    <div>Editor loading</div>
  )
}

Из документов :

useRef возвращает изменяемый объект ref, свойство .current которого инициализируется переданным аргументом (initialValue). Возвращенный объект будет сохраняться в течение всего времени жизни компонента.

0 голосов
/ 18 октября 2019

Если вы выполняете рендеринг на стороне сервера, вам необходимо динамически загрузить ваш CKeditor, потому что он взаимодействует с DOM, поэтому на сервере, так как нет браузера, он выдает эту ошибку.

 class MyEditor extends React.Component {
  state = { loading: true };

  componentDidMount() {
    this.CKEditor = require("@ckeditor/ckeditor5-react");
    this.ClassicEditor = require("@ckeditor/ckeditor5-build-classic");
    this.setState({ loading: false });
  }

  render() {
    return this.CKEditor ? (
      <this.CKEditor
        editor={this.ClassicEditor}
        data="<p>Hello from CKEditor 5!</p>"
        onInit={editor => {
          // You can store the "editor" and use when it is needed.
          console.log("Editor is ready to use!", editor);
        }}
        onChange={(event, editor) => {
          const data = editor.getData();
          console.log({ event, editor, data });
        }}
      />
    ) : (
      <div>Editor loading</div>
    );
  }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...