我有一个 NextJs 应用程序(博客),我在其中使用 React-quill 作为富文本编辑器。我正在使用 Next 自定义“应用程序”功能,其中我的 UserProvider comp 包装了所有内容,以便我可以全局访问某些内容。我的next/head comp 也在那里。
一直在阅读有关 Quill -Syntax 和 Highlight.Js 的文档,了解如何使用,但我一直收到“错误:nextjs 语法模块需要highlight.js”,我在这里缺少什么?这就是我的应用程序组件的外观:
_app.js:
function MyApp({ Component, pageProps }) {
return (
<UserProvider>
<Head>
<link rel='stylesheet' href='/css/styles.css' />
</Head>
<Nav />
<ToastContainer
position='top-center'
autoClose={2000}
pauseOnFocusLoss={false}
pauseOnHover={false}
theme='dark'
transition={Zoom}
/>
<Component {...pageProps} />
</UserProvider>
);
}
我尝试过的事情:
这里有什么帮助吗?我定制了我的 Quill 模块,因此它包含 ['code-block'],因此我已经能够拥有代码片段,但它们只是白色字体/黑色背景。这是我的 quill 自定义模块(由于 obvs 原因,语法:true 已被注释掉)
const customPostToolbar = {
// syntax: true,
toolbar: [
[{ header: [2, 3, false] }],
['bold', 'italic', 'underline', 'strike', 'blockquote'],
[
{ script: 'sub' },
{ script: 'super' },
{ list: 'ordered' },
{ list: 'bullet' },
{ indent: '-1' },
{ indent: '+1' },
],
['link', 'image'],
['code-block'],
],
};
如果有人知道的话,我很感激,昨天这件事一直困扰着我😅
安装highlight.js 导入其 css 。示例:导入 'highlight.js/styles/monokai-sublime.css';
添加这样的东西就可以了
const modules = {
//syntax: true,
syntax: {
highlight: text => hljs.highlightAuto(text).value
}
};
我们可以在客户端给窗口添加高亮,所以解决方案是:
import hljs from "highlight.js";
const ReactQuill = dynamic(
() => {
hljs.configure({ // optionally configure hljs
languages: ['javascript', 'php', 'go']
})
// @ts-ignore
window.hljs = hljs
return import ("react-quill")
}, {
ssr: false,
loading: () => <p>Loading</p>
})
const modules = {
syntax: true,
// ...
}
NextJs appdir v13以上版本的解决方案
import ReactQuill from "react-quill";
import hljs from "highlight.js/lib/common"; //common languages
interface CustomQuillProps extends ReactQuill.ReactQuillProps {
hookRef: (ref: ReactQuill | null) => void;
}
const MyReactQuill = dynamic(
async () => {
// @ts-ignore
window.hljs = hljs;
const { default: RQ } = await import("react-quill");
return function ReactQuillHoc(props: CustomQuillProps) {
const { hookRef, ...rest } = props;
// eslint-disable-next-line react/jsx-props-no-spreading
return <RQ ref={hookRef} {...{ ...rest }} />;
};
},
{
ssr: false,
loading: () => <Loading loading />
}
)}
在你的反应组件中
function MyComponent (){
return <div>
<MyReactQuill hookRef={(ref) => console.log(ref)} theme="snow"
value={value}
onChange={setValue} />;
</div/>
}
设置非特权编辑器的示例代码
function MyComponent2 (){
const UnprivilegedEditor = useRef<null | ReturnType<
ReactQuill["makeUnprivilegedEditor"]
>>(null);
return <div>
<MyReactQuill
hookRef={(ref) => {
if (ref) {
const editor = ref.getEditor();
UnprivilegedEditor.current =
ref.makeUnprivilegedEditor(editor);
}
}}
theme="snow"
value={value}
onChange={setValue} />;
</div/>
}