【发布时间】:2023-02-04 04:00:38
【问题描述】:
我将 React Quill 添加到 Next.js 项目并且它工作正常。但是当我尝试将 ImageResize 添加到编辑器时,问题就开始了。
当我添加行
Quill.register('modules/imageResize', ImageResize)
我得到一个错误
ReferenceError: 窗口未定义
我认为问题出在
Quillimport,但找不到任何有效的解决方案。文本编辑器.tsx
import { useState, useEffect } from 'react' import dynamic from 'next/dynamic' import 'react-quill/dist/quill.snow.css' import styles from '../styles/Components/TextEditor.module.scss' import ImageResize from 'quill-image-resize-module-react' import { Quill } from 'react-quill' const ReactQuill = dynamic(() => import('react-quill'), { ssr: false }) Quill.register('modules/imageResize', ImageResize) interface TextEditorParams { onChange: (value: string) => string | void placeholder?: string error?: boolean defaultValue?: string | undefined required?: boolean } const TextEditor = ({ onChange, placeholder, error, defaultValue, required }: TextEditorParams) => { const [errorState, setErrorState] = useState<boolean | undefined>(false) useEffect(() => { let shouldUpdate = true if (shouldUpdate) { setErrorState(error) } return () => { shouldUpdate = false } }, [error]) const modules = { toolbar: { container: [ [{ header: [1, 2, 3, 4, 5, 6, false] }], ['bold', 'italic', 'underline', 'strike'], [{ list: 'ordered' }, { list: 'bullet' }], [{ align: [] }], ['link', 'image'], ['clean'] ] }, imageResize: { parchment: Quill.import('parchment'), modules: ['Resize', 'DisplaySize', 'Toolbar'] } } const changeValue = (value: string) => { onChange(value) } return ( <div className={styles.editor}> <ReactQuill modules={modules} defaultValue={defaultValue} onChange={(value) => changeValue(value)} placeholder={`${placeholder} ${required ? '*' : ''}`} className={errorState ? 'textEditor__error' : 'textEditor'} /> </div> ) } export default TextEditor
【问题讨论】:
-
您必须保护此导入不在服务器上运行。 (它在 nextjs ssr 部分上运行)。您可以使用动态导入或仅在 clinet 上的组件渲染器中渲染此组件(文本编辑器)。 nextjs.org/docs/advanced-features/dynamic-import#with-no-ssr
-
我没有考虑使用动态导入我的
TextEditor组件。这解决了我的问题。但我不喜欢每次我想使用这个组件时都必须使用动态导入,也许在组件内部有更微妙的解决方案?
标签: reactjs typescript next.js react-quill