本文主要是介绍NextJS开发:nextjs中使用CkEditor5,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
NextJS项目中需要使用CkEditor5作为富文本编辑器,按照官网React CkEditor5手册使用出现如下错误:
node_modules/@ckeditor/ckeditor5-react/dist/index.js (5:242) @ eval⨯ ReferenceError: self is not defined
还是因为nextjs的服务器端渲染造成的错误,富文本编辑器一般用在表单提交页面,没有使用ssr的必要,想要解决上面问题,动态导入组件,禁用ssr就可以解决。
1、封装ckeditor组件
"use client"import { CKEditor } from '@ckeditor/ckeditor5-react';
import ClassicEditor from '@ckeditor/ckeditor5-build-classic';export function CustomCkEditor(props: {data: string, onChange: (content: string)=>void}) {const editorConfiguration = {toolbar: ['heading', //类型'|','bold', //加粗'italic', //斜体'link', //超链接'bulletedList',// 无序列表'numberedList', //有序列表'|','indent', //左缩进'outdent', //右缩进'|','imageUpload', //图片上传'blockQuote', //引用'insertTable', //插入图标//'mediaEmbed', //视频上传'undo', //撤销'redo'//重做]};return (<CKEditorconfig={ editorConfiguration }editor={ ClassicEditor }data={ props.data }onReady={ 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();props.onChange(data)console.log( { event, editor, data } );} }onBlur={ ( event, editor ) => {console.log( 'Blur.', editor );} }onFocus={ ( event, editor ) => {console.log( 'Focus.', editor );} }/>)
}
2、动态导入、禁用ssr
import dynamic from 'next/dynamic'...const CustomCkEditor = dynamic(() => import('@/components/app/custom-ckeditor').then((mod) => mod.CustomCkEditor), { ssr: false })const [content, setContent] = React.useState("");return (<><CustomCkEditor data={content} onChange={(content: string)=>setContent(content)}/></>
)
这篇关于NextJS开发:nextjs中使用CkEditor5的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!