大家好,我想要为我的 nextjs 项目提供一个所见即所得的编辑器。经过一番研究后,我决定在我的项目中使用 ckeditor5。我正在将 next14 与 typescript 和 src 目录一起使用。
我想知道我是否可以将它放在 src 目录而不是根文件夹中?这行得通吗?这是最佳实践吗?
文档中提到将其放置在此处的根目录中:https://ckeditor.com/docs/ckeditor5/latest/installation/integrations/next-js.html。
`
/src
/ckeditor5
/build
- ckeditor.ts
/app
- layout.tsx
- page.tsx
/components
/editor
....
/firebase
/public
/images
... (static images)
将ckeditor5插入nextjs src目录
是的,你可以将你的CKeditor放在你的Next js项目的“src”目录中,我想将它放在src中会是一个更好的选择,因为它会更容易组织和管理,我也在使用nextjs 13(应用程序路由器),我已将编辑器放在 src 文件夹中。结构看起来像这样
src/components/helpers/CKEditor/index.js
下面是我在项目中使用 CKEditor 的方式。
import React, {
useEffect,
useRef,
useState
} from "react";
import Snackbar from "@mui/material/Snackbar";
import Alert from "@mui/material/Alert";
export default function CKeditor({
onChange,
value,
name,
isDisabled,
handleTextCount,
wordLimit,
}) {
const editorRef = useRef();
const [open, setOpen] = useState(false);
const {
CKEditor,
ClassicEditor
} = editorRef.current || {};
const handleChange = (event, editor) => {
const content = editor.getData();
const text = content.replace(/<[^>]*>/g, "").replace(/ /g, " ");
const remainingWords = wordLimit - text.length;
if (remainingWords >= 0 && text.length < 1501) {
handleTextCount(remainingWords);
onChange(content);
} else {
editor.setData(value);
setOpen(true);
}
};
useEffect(() => {
editorRef.current = {
CKEditor: require("@ckeditor/ckeditor5-react").CKEditor,
ClassicEditor: require("@ckeditor/ckeditor5-build-classic"),
};
}, []);
return ( <
> {
editorRef.current ? ( <
CKEditor data = {
value
}
config = {
{
toolbar: ["bold", "italic", "link", "bulletedList", "numberedList"],
}
}
disabled = {
isDisabled
}
name = {
name
}
editor = {
ClassicEditor
}
onChange = {
handleChange
}
/>
) : ( <
div > Editor loading < /div>
)
}
<
Snackbar anchorOrigin = {
{
vertical: "top",
horizontal: "center"
}
}
open = {
open
}
autoHideDuration = {
6000
}
onClose = {
() => setOpen(false)
} >
<
Alert onClose = {
() => setOpen(false)
}
severity = "warning"
sx = {
{
width: "100%"
}
} >
Text length exceeds!
<
/Alert> <
/Snackbar> <
/>
);
}
并在我的其他组件中调用它,如下所示
"use client";
import React, {
useState
} from "react";
import CKeditor from "@/components/helpers/CKEditor";
const MarkdownEditor = () => {
const WORD_LIMIT = 1500;
const [textCount, setTextCount] = useState(WORD_LIMIT);
return ( <
>
<
CKeditor name = "post_description"
value = {
watch("description")
}
onChange = {
(newValue) => {
setValue("description", newValue);
}
}
handleTextCount = {
(newTextCount) => setTextCount(newTextCount)
}
wordLimit = {
WORD_LIMIT
}
/> <
/>
);
};
export default MarkdownEditor;
我只是想举个例子,向您展示我的代码,在将其粘贴到此处之前,我已经删除了很多内容,所以不要指望它能够完美运行,我只是想让您在放置它时向您展示它工作得绝对正常在 src 文件夹内。