2 回答
![?](http://img1.sycdn.imooc.com/54585094000184e602200220-100-100.jpg)
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)}
/>
![?](http://img1.sycdn.imooc.com/54584f850001c0bc02200220-100-100.jpg)
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。
添加回答
举报