是的,您的分析是正确的。代码片段令人震惊。React中在DOM元素最终可用时初始化任何代码的正确方法是通过回调引用
我目前正在尝试创建一个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元素";图像助手";。handleImage事件负责创建croppieInstance。但当它被调用时,它似乎没有被渲染,因此无法创建任何croppie实例。
我的假设正确吗?
如果是这样的话,React纠正代码的方法是什么?
感谢您的帮助
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>
)}