next.js 未定义React Quill窗口

rn0zuynd  于 2022-11-05  发布在  React
关注(0)|答案(1)|浏览(142)

我将React Quill添加到Next.js项目中,它工作正常。但是当我尝试将ImageResize添加到编辑器中时,问题就开始了。
当我添加行

Quill.register('modules/imageResize', ImageResize)

我收到错误
参考错误:未定义窗口
我认为问题是与Quill导入,但找不到任何工作的解决方案。
TesxtEditor.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
iqjalb3h

iqjalb3h1#

将您的组件 Package 在此hellper组件中。

若要在客户端动态加载组件,可以使用ssr选项禁用服务器呈现。如果外部依赖项或组件依赖于浏览器API**(如window),则此选项非常有用。**

docs无ssr导入

import React from 'react';
import dynamic from 'next/dynamic';

const NoSSR = ({ children }) => (
  <>{children}</>
);

export default dynamic(() => Promise.resolve(NoSSR), {
  ssr: false,
});

就这样:

import NoSSR from "NoSSR"
import {TextEdior as TextEditortQuill} from "./TextEditor"

const TextEditor = ({...props}) => {

   return (
     <NoSSR>
       <TextEditortQuill {...props}>
     </NoSSR>
   )
}

export default TextEditor;

相关问题