我想在我的react项目中实现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:未在对象处定义窗口。(/Users/bobbyjulian/Desktop/project/test/node_modules/ ckeditor/ckeditor5-react/dist/ckeditor.js:5:244 Module._compile内部/模块/cjs/loader.js:778:30 Module._extensions..js内部/模块/cjs/loader.js:789:10 Module.load内部/模块/cjs/loader.js:653:32 tryModuleLoad内部/模块/cjs/loader.js:593:12
我真的很感激你的回答。谢谢。
发布于 2019-10-27 05:42:49
下面是一个使用NextJS和的工作示例。我们可以利用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'), // depricated in v3
CKEditor: require('@ckeditor/ckeditor5-react').CKEditor // v3+
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)。返回的对象将持续到组件的整个生命周期。
发布于 2019-10-18 08:55:40
如果您正在进行服务器端呈现,那么您需要动态加载您的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>
);
}
}发布于 2021-03-12 17:35:20
动态导入将解决这个问题。
https://stackoverflow.com/questions/58447134
复制相似问题