react-quill
在客户端动态导入
ssr: false
。我的功能组件工作正常,我想将
quill-blot-formatter
包添加到我的鹅毛笔组件的
modules
部分。我的第一个障碍是,我无法使用
quill-blot-formatter
注册此
Quill
,如图所示:
ServerError
ReferenceError: document is not defined
这个页面是客户端渲染的,因此我不明白这个错误是从哪里来的!这是我的代码:
import dynamic from "next/dynamic";
import BlotFormatter from "quill-blot-formatter";
const QuillNoSSRWrapper = dynamic(import('react-quill'), {
ssr: false,
loading: () => <p>Loading...</p>,
})
Quill.register("modules/blotFormatter", BlotFormatter);
在这里,我不明白如何将 Quill
从
react-quill
中取出,因为它是动态导入的。因此,我认为
Quill.register
不起作用。现在,我如何用
quill-blot-formatter
注册
react-quill
?按照使用react-quill的Next.js示例,我什至没有像包中的默认导出那样将react-quill导入为
ReactQuill
。然后我像这样声明了
blotFormatter
模块。
const modules = {
blotFormatter: {}, // here
toolbar: [
[{header: '1'}, {header: '2'}, {font: []}],
[{size: []}],
...
],
}
const formats = ['header','font','size','bold','italic','underline',...]
并在render()
方法中使用,如下所示:
export default function NewContent() {
...
render(
<QuillNoSSRWrapper
className={styles.quillTextArea}
id="quilleditor"
modules={modules}
formats={formats}
theme="snow"
onChange={handleTextChange}
readOnly={false}
/>
);
}
到目前为止,这个 QuillNoSSRWrapper
子组件做得很好,但是,我如何在它的
quill-blot-formatter
中使用
formats
?
const ReactQuill = dynamic(
async () => {
const { default: RQ } = await import("react-quill");
const { default: BlotFormatter } = await import("quill-blot-formatter");
RQ.Quill.register("modules/blotFormatter", BlotFormatter);
return function forwardRef({ forwardedRef, ...props }) {
return <RQ ref={forwardedRef} {...props} />;
};
},
{
ssr: false,
}
);
使用此代码,您可以导入 ReactQuill,注册您的模块并传递稍后可以使用的引用请参阅下面的详细信息。因此,使用此代码,您现在不需要任何状态。此外,您可以将自定义加载功能添加到动态详细信息。
import dynamic from 'react/dynamic'
const ReactQuill = dynamic(() => import("react-quill"), { ssr: false });
或者如果你想像这样传递引用
const ReactQuill = dynamic(
async () => {
const { default: RQ } = await import("react-quill");
// eslint-disable-next-line react/display-name
return ({ forwardedRef, ...props }) => <RQ ref={forwardedRef} {...props} />;
},
{
ssr: false,
}
);
然后你可以像这样使用 ref因此,在客户端导入 ReactQuill 后,您需要注册模块,我找到了这个解决方案
<ReactQuill ... forwardedRef={quillRef}/>
here,它看起来很奇怪,我没有时间改进它,但它有效。这是代码。
const loadQuill = async () => {
return new Promise(async (resolve, reject) => {
const Quill = await require("react-quill").Quill;
const BlotFormatter = (await import("quill-blot-formatter")).default;
resolve({ Quill, BlotFormatter });
})
.then(({ Quill, BlotFormatter }) => {
Quill.register("modules/blotFormatter", BlotFormatter);
return;
})
.then((value) => {
setEnableEditor(true);
});
};
useEffect(() => {
loadQuill();
}, []);
此代码将在客户端注册模块上执行。另外,正如您所看到的,您需要声明状态enableEditor。并且仅当enableEditor为true时才渲染ReactQuill
{enableEditor && <ReactQuill ... />}
看起来有点奇怪所以也许我稍后会更新