1

我目前正在尝试创建一个 React 组件来使用 Croppie 库上传和裁剪图像。

我找到了这个代码示例

import "croppie/croppie.css"
import { Button, Grid } from "@material-ui/core"
import * as React from "react"
import Croppie from "croppie"

export function CroppieExample() {
  const [image, setImage] = React.useState("")
  const [croppie, setCroppie] = React.useState<Croppie | null>(null)

  function handleImage(image: string) {
    setImage(image)
    const el = document.getElementById("image-helper")
    if (el) {
      const croppieInstance = new Croppie(el, {
        enableExif: true,
        viewport: {
          height: 250,
          width: 250,
        },
        boundary: {
          height: 280,
          width: 400,
       }
    });
    croppieInstance.bind({
      url: image,
    });
    setCroppie(croppieInstance)
    }
  }

  function handleSubmit(event: any) {
    event.preventDefault()
    if (croppie !== null) {
      croppie.result({type: 'base64',
      size: {
          width: 480,
          height: 480
      }}).then((blob) => {
        console.log(blob)
      }
      )
    }
  }

  return (
    <form onSubmit={handleSubmit}>
      <Grid container spacing={2}>
        {image === "" && (
            <Grid item xs={12}>
                {/* Your image upload functionality here */}
                <ImageUpload image={image} setImage={handleImage} />
            </Grid>
            )}
        {image !== "" && (
            <Grid item container justify="center" xs={12}>
              <div id="image-helper"></div>
            </Grid>
            )}
        <Grid container item xs={12} justify="flex-end">
          <Button color="primary" variant="contained" type="submit">
            Submit
          </Button>
        </Grid>
      </Grid>
    </form>
  )
}

我对这段代码的条件部分有疑问:

为了工作,必须将 Croppie 实例附加到 div 元素“image-helper”。handleImage 事件负责创建croppieInstance。但是到它被调用时,它似乎没有被渲染,因此无法创建croppie 实例。

我的假设对吗?

如果是这样,纠正代码的 React 方法是什么?

感谢您的帮助

4

1 回答 1

0

是的,你的分析是正确的。代码片段令人震惊。当 DOM 元素最终可用时,React 中初始化任何代码的正确方法是通过回调 ref。

const initImageHelper = useCallback(
  (element) => {
    if (element) {
      const croppieInstance = new Croppie(element, settings);
      croppieInstance.bind({ url: image });
      setCroppie(croppieInstance);
    }
  }, [image]
);


          {image !== "" && (
            <Grid item container justify="center" xs={12}>
              <div id="image-helper" ref={initImageHelper}></div>
            </Grid>
          )}
于 2021-05-06T08:03:43.440 回答