如何使用 CKEditor 和 React JS 捕获 OnChange 事件

Posted

技术标签:

【中文标题】如何使用 CKEditor 和 React JS 捕获 OnChange 事件【英文标题】:How To Capture OnChange Event Using CKEditor with React JS 【发布时间】:2020-05-30 05:25:30 【问题描述】:

我正在使用 React、Django 和 Graphene 构建一个博客应用程序。我想将 CKEditor 组件集成到 React 前端,但我似乎能够从 CKEditor 获取数据并存储在状态中。每次我在文本字段中输入时,我都会收到以下错误“CKEditorError:无法读取未定义的属性'值'”。如果您能帮助指出我做错了什么或没有做什么,我将不胜感激。我的代码如下。

import React,  useState, Fragment  from "react";
import  Mutation  from "react-apollo";
import  gql  from "apollo-boost";
import axios from "axios";

import CKEditor from '@ckeditor/ckeditor5-react';
import ClassicEditor from '@ckeditor/ckeditor5-build-classic';

import  makeStyles  from "@material-ui/core/styles";

import 
  Button,
  Input,
  TextField,
  Container,
  Typography
 from "@material-ui/core";

const useStyles = makeStyles(theme => (
  paper: 
    marginTop: theme.spacing(12),
    display: "flex",
    flexDirection: "column",
    alignItems: "center"
  ,
  avatar: 
    margin: theme.spacing(1),
    backgroundColor: theme.palette.secondary.main
  ,
  form: 
    width: "100%", // Fix IE 11 issue.
    marginTop: theme.spacing(1)
  ,
  submit: 
    margin: theme.spacing(3, 0, 2)
  
));

const CreatePost = () => 
  const classes = useStyles();
  // const [open, setOpen] = useState(false);
  const [title, setTitle] = useState("");
  const [content, setContent] = useState("");
  const [file, setFile] = useState("");
  const [submitting, setSubmitting] = useState(false);

  const handleImageChange = event => 
    const selectedFile = event.target.files[0];
    setFile(selectedFile);
  ;

  const handleImageUpload = async () => 
    try 
      const data = new FormData();
      data.append("file", file);
      data.append("resource_type", "image");
      data.append("upload_preset", "nanan");
      data.append("cloud_name", "nana");

      const res = await axios.post(
        "https://api.cloudinary.com/v1_1/nana/image/upload/",
        data
      );
      console.log(res.data.url);
      return res.data.url;
     catch (error) 
      console.error("Error uploading file", error);
      setSubmitting(false);
    
  ;

  const handleSubmit = async (event, createPost) => 
    event.preventDefault();
    setSubmitting(true);
    const uploadUrl = await handleImageUpload();
    createPost( variables:  title, content, thumb: uploadUrl  );
  ;

  return (
    <Container component="main" maxWidth="xs">
      <div className=classes.paper>
        <Typography component="h1" variant="h5">
          Create A Post
        </Typography>
        <Mutation
          mutation=CREATE_POST_MUTATION
          onCompleted=data => 
            setSubmitting(false);
            setTitle("");
            setContent("");
            setFile("");
          
        >
          (createPost,  loading, error ) => 
            if (error) return <div>error!!!</div>;
            return (
              <form
                className=classes.form
                onSubmit=event => handleSubmit(event, createPost)
              >
                <TextField
                  autoFocus
                  label="Title"
                  type="text"
                  id="title"
                  required
                  onChange=event => setTitle(event.target.value)
                  margin="normal"
                  required
                  fullWidth
                  name="title"
                  autoComplete="title"
                />

<CKEditor
                  editor= ClassicEditor 
                  name="content"
                  label="Content"
                  type="text"
                  id="content"
                  onChange=event => setContent(event.target.value)
                />

                <Input
                  type="file"
                  fullWidth
                  id="image"
                  required
                  type="file"
                  accept="image/png, image/jpeg"
                  onChange=handleImageChange
                />
                <Button
                  type="submit"
                  fullWidth
                  variant="contained"
                  color="primary"
                  className=classes.submit
                  disabled=
                    submitting || !title.trim() || !content.trim() || !file
                  
                >
                  loading ? "Submitting ..." : "Submit"
                </Button>
              </form>
            );
          
        </Mutation>
      </div>
    </Container>
  );
;

export default CreatePost;

const CREATE_POST_MUTATION = gql`
  mutation($title: String!, $content: String, $thumb: String!) 
    createPost(title: $title, content: $content, thumb: $thumb) 
      post 
        id
        title
        content
        thumb
        createdAt
        slug
      
    
  
`;

【问题讨论】:

错误的事件处理程序,阅读 cke 文档 我已阅读文档,但似乎无法理解为什么我无法正确理解。如果你能指出来,它会继续的,谢谢 ckeditor.com/docs/ckeditor5/latest/builds/guides/integration/… 我已经修好了!这只是一个菜鸟的错误 【参考方案1】:

1。安装ckeditor

https://ckeditor.com/docs/ckeditor5/latest/builds/guides/integration/frameworks/react.html

2。代码示例(带有 React 钩子)

import CKEditor from "@ckeditor/ckeditor5-react";
import ClassicEditor from "@ckeditor/ckeditor5-build-classic";

function Example()
    const [data, setData] = React.useState('');
    const handleSubmit = (event) => 
        event.preventDefault();
        // Define your onSubmit function here
        // ...
    ;

    const inputHandler = (event, editor) => 
        console.log(editor.getData());
        // Define your onSubmit function here
        // ...
        // for example, setData() here

    ;

    return(
        <div className="Sumbit">
          <div>
            <form onSubmit=handleSubmit>
              <div>
                <CKEditor
                  id="inputText"
                  editor=ClassicEditor
                  onChange=inputHandler
                />
              </div>
            </form>
          </div>
        </div>
    )


export default Example;

【讨论】:

以上是关于如何使用 CKEditor 和 React JS 捕获 OnChange 事件的主要内容,如果未能解决你的问题,请参考以下文章

如何在 React CKEDITOR 中添加占位符

如何在 Nuxt.js 中使用 CKEditor - 未定义窗口错误

如何配置与使用CKEDITOR

如何设置ckeditor的编辑器,在哪里设置

Ckeditor 不能在 laravel 5.5 的 vue js 中工作

CKEditor配置 - 如何在使用Builder自动构建之后手动安装另外一个插件