如何在 React Quill 图像处理程序中访问道具

how to access props in react quill image handler

我正在为我的项目使用 React quill 编辑器,并使用我的后端服务器上传图片,但我需要访问 React quill 的图像处理程序中的道具,但我无法这样做,因为无法访问内部的这个对象图像处理程序。 这是我的编辑器代码。

<ReactQuill
  ref={(el) => (this.quillRef = el)}
  onChange={this.handleChange}
  placeholder={"share your thoughts"}
  modules={{
    toolbar: {
      container: [
        [{ header: "1" }, { header: [2, 3, 4, 5, 6] }, { font: [] }],
        [{ size: ["small", false, "large", "huge"] }],
        ["bold", "italic", "underline", "strike", "blockquote"],
        [{ list: "ordered" }, { list: "bullet" }],

        ["link", "image", "video"],
        ["clean"],
        ["code-block"],
        [{ color: [] }, { background: [] }], // dropdown with defaults from theme

        [{ align: [] }],
      ],
      handlers: {
        image: this.imageHandler,
      },
    },
  }}
/>;

function imageHandler() {
  let self = this;
  let image;
  let image_extension;
  const Cryptr = require("cryptr");
  const cryptr = new Cryptr(key);
  const users = localStorage.getItem("users")
    ? JSON.parse(cryptr.decrypt(localStorage.getItem("users")))
    : {};
  // console.log(users[users.lastLoginId])
  let loggedinUser = users[users.lastLoginId];
  const input = document.createElement("input");

  input.setAttribute("type", "file");
  input.setAttribute("accept", "image/*");
  input.setAttribute("class", "Editor-mage");
  input.click();

  input.onchange = async () => {
    //debugger
    const file = input.files[0];

    var ValidImageTypes = [
      "image/gif",
      "image/jpeg",
      "image/png",
      "image/jpg",
      "image/GIF",
      "image/JPEG",
      "image/PNG",
      "image/JPG",
    ];
    let file_type = file.type;
    let filename = file.name;
    let extension = filename.split(".").pop();
    if (ValidImageTypes.indexOf(file_type) >= 0) {
      if (true) {
        var fileToLoad = file;

        loadImage(
          fileToLoad,
          (canvas) => {
            if (canvas) {
              // this.setState({
              image = canvas.toDataURL();
              image_extension = extension;
              //});

              const res = new Promise(function (resolve, reject) {
                axios({
                  method: "post",
                  url: API_URL + "api/v1/postblogimage",
                  headers: {
                    "x-access-handler": loggedinUser.token,
                  },
                  data: {
                    image: image,
                    image_extension: image_extension,
                    userid: loggedinUser.userid,
                  },
                })
                  //axios.post(API_URL + 'api/v1/postblogimage', formData, config)
                  .then((response) => {
                    //debugger
                    if (
                      response.data.error == "false" ||
                      response.data.error == false
                    ) {
                      if (
                        response.data.status == 200 &&
                        response.data.message == "Image uploaded successfully"
                      ) {
                        //debugger
                        const range = self.quill.getSelection(true);

                        // Insert temporary loading placeholder image
                        // this.quill.insertEmbed(range.index, 'image', `${window.location.origin}/images/loaders/placeholder.gif`);

                        // Move cursor to right side of image (easier to continue typing)
                        self.quill.setSelection(range.index + 1);

                        // Remove placeholder image
                        self.quill.deleteText(range.index, 1);

                        // Insert uploaded image
                        let url = response.data.data[0].imageURL;
                        self.quill.insertEmbed(range.index, "image", url);
                        self.quill.pasteHTML(
                          range.index,
                          <img
                            src={url}
                            class="blog-image-content"
                            alt="Responsive image"
                          />
                        );
                      }
                    }

                    // }
                  })
                  .catch((error) => {
                    // reject(Error("It broke"));
                  });
              });
            }
          },
          { orientation: true }
        );
      } else {
        // this.setState({
        // image_warning:'File size larger than maximum allowed limit',
        image = "";
        image_extension = "";
        // })
        this.fileInput.value = "";
      }
    } else {
    }
  };
}

谁能帮我解决这个问题,因为我在这个问题上被困了很长时间。 任何帮助和建议将不胜感激。

我认为你可以使用高阶函数。

image: this.imageHandler(props)
...
function imageHandler(props) {
  return function() {
    let self = this;
    let image;
    ...
  }
}

我阅读了 Quilljs 的文档。

Handler functions will be bound to the toolbar (so using this will refer to the toolbar instance) and passed the value attribute of the input if the corresponding format is inactive, and false otherwise. Adding a custom handler will overwrite the default toolbar and theme behavior.

并发现 imageHandler 将在工具栏的上下文中调用,因此 this.props 在调用时不会按预期工作。

所以要实现对 props 的访问,你可以这样做:

handlers: {
    image: (val) => this.imageHandler({ val, componentProps: this.props });
  }

在 imageHandler 中,您可以像这样访问它:

function imageHandler({ val, componentProps }) {
  // componentProps has all your propss, try to print it and see
  // rest of your code, instead of this.props.something take componentProps.something
}

如果有帮助请告诉我。谢谢