我目前正在尝试创建一个 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 方法是什么?
感谢您的帮助