【问题标题】:CKEditor display text with NextJS using useState()CKEditor 使用 NextJS 使用 useState() 显示文本
【发布时间】:2020-02-25 10:56:06
【问题描述】:

大家,

我正在尝试在我的 NextJS 项目中实现 CKEditor。

但是我有一个问题,我在另一个 div 中写的文字无法显示。

我每次总是出错,我是 NextJS 的新手,所以我很难过。

这是我的组件的代码:

import React, {useState, useEffect, useRef} from 'react';

function Article() {

  const editorRef = useRef()
  const [editorLoader, setEditorLoaded] = useState(false)
  const {CKEditor, ClassicEditor} = editorRef.current || {}
  const [data, setData] = useState('')

  useEffect(() => {
    editorRef.current = {
      CKEditor: require('@ckeditor/ckeditor5-react'),
      ClassicEditor: require('@ckeditor/ckeditor5-build-classic')
    }
    setEditorLoaded(true)
  }, [])


  function onEditorChange(evt) {
    setData(evt.editor.getData())
  }


  return editorLoader ? (
    <div>
      <p style={{display: 'block'}}>{data}</p>
      <CKEditor
        editor={ClassicEditor}
        data={data}
        onChange={onEditorChange}
      />
    </div>
  ) : (
    <div>Chargement...</div>
  )
}

export default Article

以及每次我尝试更改文本时都会遇到的错误:

CKEditorError: Cannot read property 'getData' of undefined

onEditorChange [as onChange]
./components/news/Article.js:20
  17 | 
  18 | 
  19 | function onEditorChange(evt) {
> 20 |   setData(evt.editor.getData())
     | ^  21 | }
  22 | 
  23 | 

【问题讨论】:

  • 你能console.logevt。我猜editor 不在evt 中。
  • 确实,这很奇怪,因为它在文档中是这样使用的

标签: javascript reactjs ckeditor state next.js


【解决方案1】:

CKEditor 组件在 onChange 属性中接收具有 2 个参数的函数 - eventeditor

<CKEditor
    ...
    onChange={(event, editor) => ...}

因此,您可以编写 onEditorChange 函数,例如:

function onEditorChange(event, editor) {
  setData(editor.getData())
}

Official Docs CKEditor

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-05-14
    • 2023-01-11
    • 1970-01-01
    • 1970-01-01
    • 2021-09-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多