2 回答

TA貢獻1854條經驗 獲得超8個贊
你可以使用 Promise 解決這個問題,
function resizeImage(file: IHTMLInputEvent, width: number) {
return new Promise((resolve, reject) => {
const fileName = file.target.files[0].name;
const reader = new FileReader();
reader.readAsDataURL(file.target.files[0]);
reader.onload = (event) => {
const img = new Image();
img.src = event.target.result.toString();
img.onload = () => {
const elem = document.createElement('canvas');
const scaleFactor = width / img.width;
elem.width = width;
elem.height = img.height * scaleFactor;
const ctx = elem.getContext('2d');
ctx.drawImage(img, 0, 0, width, img.height * scaleFactor);
ctx.canvas.toBlob((blob) => {
resolve(new File([blob], fileName, {
type: 'image/jpeg',
lastModified: Date.now()
}));
}, 'image/jpeg', 1);
};
};
});
}
隨著async, await,
async function handleUpload(e: IHTMLInputEvent) {
const resizedImage = await resizeImage(e, 600);
// do you suff here
}
JSX,
<input
className={classes.inputForUpload}
accept='image/*'
type='file'
ref={uploadImage}
onChange={async (e: IHTMLInputEvent) => await handleUpload(e)}
/>

TA貢獻1802條經驗 獲得超5個贊
請問您為什么不喜歡使用狀態的解決方案?這似乎是一個非常標準的用例。
您的狀態可能如下所示:
state = {
imageDescription: '',
imageUrl: null
};
您的操作處理程序將在成功時簡單地設置狀態,如下所示:
img.onload = () => {
...
this.setState({ imageDescription: fileName, imageSrc: img.src })
};
最后你的渲染函數看起來像這樣:
render() {
const { imageDescription, imageUrl } = this.state;
return (
<Fragment>
<input
className={classes.inputForUpload}
accept='image/*'
type='file'
ref={uploadImage}
onChange={(e: IHTMLInputEvent) => handleUpload(e)}
/>
<img src={imageUrl} alt={imageDescription} />
</Fragment>
)
}
PS你可以刪除handleUpload,直接調用resizeImage。
添加回答
舉報