按照官方文档里面React的集成方法做,从其他页面跳转到编辑器页面是没有问题的,但是你要点击刷新按钮刷新整个编辑器所在页面时就会报错了:ReferenceError: self is not defined
本文解决的是这个问题。
新增文件components/Editor.jsx
:
import React, { useEffect, useRef } from "react";
const editorCfg = {
language: 'zh-cn'
}
function Editor({ onChange, editorLoaded, name, data }) {
const editorRef = useRef();
const { CKEditor, ClassicEditor } = editorRef.current || {};
useEffect(() => {
editorRef.current = {
CKEditor: require("@ckeditor/ckeditor5-react").CKEditor, // v3+
ClassicEditor: require("@ckeditor/ckeditor5-build-classic"),
// 引入本地化文件
zhCn: require('@ckeditor/ckeditor5-build-classic/build/translations/zh-cn')
};
}, []);
return (
<div>
{editorLoaded ? (
<CKEditor
name={name}
config={editorCfg}
editor={ClassicEditor}
data={data}
onChange={onChange}
onReady={(editor) => {
// You can store the "editor" and use when it is needed.
console.log("Editor is ready to use!", editor);
// 这里是设置编辑器最小高度,默认没内容高度太矮了
editor.editing.view.change((writer) => {
writer.setStyle(
"min-height",
"200px",
editor.editing.view.document.getRoot()
);
});
}}
/>
) : (
<div>Editor loading</div>
)}
</div>
);
}
export default Editor;
在要使用页面引入上面的组件import Editor from '@/components/Editor'
。
// class 组件
import React, { Component } from 'react';
import Editor from '@/components/Editor'
export default class Page extends Component{
constructor(props) {
super(props);
this.state = {editorLoaded: false};
}
componentDidMount() {
this.setState({editorLoaded: true})
}
render() {
return (
<div>
<Editor
editorLoaded={this.state.editorLoaded}
data="<p>Hello from CKEditor 5!</p>"
onChange={ ( event, editor ) => {
const data = editor.getData();
console.log( { event, editor, data } );
} }
/>
</div>
)
}
}
// 函数组件
import React, { useState, useEffect } from "react";
import Editor from '@/components/Editor'
export default function Page() {
const [editorLoaded, setEditorLoaded] = useState(false);
useEffect(() => {
setEditorLoaded(true);
}, []);
return (
<div>
<h1>ckEditor 5</h1>
<Editor
name="description"
onChange={ ( event, editor ) => {
const data = editor.getData();
console.log( { event, editor, data } );
} }
editorLoaded={editorLoaded}
/>
</div>
);
}
这样不管怎么样都不会报xx not defined
了。
参考文章:https://dev.to/devzversity/how-to-add-ckeditor5-in-your-next-js-react-app-1be7
本来链接:https://360us.net/article/85.html