我想在我的反应项目中实现 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;
Run Code Online (Sandbox Code Playgroud)
我收到以下错误
参考错误:窗口未在对象中定义。(/Users/bobbyjulian/Desktop/project/test/node_modules/ckeditor/ckeditor5-react/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 internal/modules/cjs/loader.js:653:32 tryModuleLoad internal/modules/cjs/loader.js:593:12
我真的很感激任何答案。谢谢你。
Bil*_*our 20
这是 NextJS 和 React Hooks 的工作示例。我们可以利用useRef
来保持 Editor 实例。
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>
)
}
Run Code Online (Sandbox Code Playgroud)
从文档:
useRef
返回一个可变的 ref 对象,其.current
属性被初始化为传递的参数 (initialValue
)。返回的对象将在组件的整个生命周期内持续存在。