简体   繁体   中英

how to access props in react quill image handler

i am using react quill editor for my project and using my backend server to image upload but i need to access props inside the image handler of react quill and i am unable to do so as not able to access this object inside image handler. here is my editor code.

<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 {
    }
  };
}

can someone please help me out with this one as i am stuck for long on this. any help and suggestion will be greatly appreciated.

I think you can use higher order function.

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

I read the documentation of 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.

and found out the imageHandler will be called in the context of the toolbar, so this.props will not work as intended when it is called.

so to achieve the accesss to props, you can do something like this:

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

In the imageHandler you can access it like this:

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
}

Let me know if it helps. Thanks

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM