gpt4 book ai didi

reactjs - (CKEditor) 实现时未定义 ReactJS 窗口

转载 作者:行者123 更新时间:2023-12-02 16:37:28 25 4
gpt4 key购买 nike

我想将 CKEditor 实现到我的 React 项目中。但是,我在尝试加载它时收到错误。我一直在关注所有官方文档。我不知道为什么,无论如何这是我的代码

import React from 'react';

class MyEditor extends React.Component {
state = {loading: true};

componentDidMount() {
this.CKEditor = require("@ckeditor/ckeditor5-react");
this.ClassicEditor = require("@ckeditor/ckeditor5-build-classic");
this.setState({ loading: false });
}

render() {
return ({this.CKEditor && (<this.CKEditor editor={this.ClassicEditor} data="<p>Hello from CKEditor 5!</p>"
onInit={ editor => {
// You can store the "editor" and use when it is needed.
console.log( 'Editor is ready to use!', editor );
} }
onChange={ ( event, editor ) => {
const data = editor.getData();
console.log( { event, editor, data } );
} }/>)})
}
}

export default MyEditor;

我收到以下错误

ReferenceError: window is not defined at Object. (/Users/bobbyjulian/Desktop/project/test/node_modules/ ckeditor/ckeditor5-react/dist/ckeditor.js:5:244 Module._compile internal/modules/cjs/loader.js:778:30 Module._extensions..js internal/modules/cjs/loader.js:789:10 Module.load internal/modules/cjs/loader.js:653:32 tryModuleLoad internal/modules/cjs/loader.js:593:12

我真的很感谢任何回答。谢谢。

最佳答案

这是一个使用 NextJS 和 React Hooks 的工作示例。我们可以利用 useRef 来保留 Editor 实例。

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

export default function MyEditor () {
const editorRef = useRef()
const [editorLoaded, setEditorLoaded] = useState(false)
const { CKEditor, ClassicEditor } = editorRef.current || {}

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

return editorLoaded ? (
<CKEditor
editor={ClassicEditor}
data='<p>Hello from CKEditor 5!</p>'
onInit={editor => {
// You can store the "editor" and use when it is needed.
console.log('Editor is ready to use!', editor)
}}
onChange={(event, editor) => {
const data = editor.getData()
console.log({ event, editor, data })
}}
/>
) : (
<div>Editor loading</div>
)
}

来自docs :

useRef returns a mutable ref object whose .current property is initialized to the passed argument (initialValue). The returned object will persist for the full lifetime of the component.

关于reactjs - (CKEditor) 实现时未定义 ReactJS 窗口,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58447134/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com