【发布时间】:2020-11-08 11:22:54
【问题描述】:
我有一个在 React 应用程序中从头开始构建的图像上传器。图像预览 - 感谢 window.URL.createObjectURL() - 仅在第一次工作。我认为这是因为内存问题,所以我在每次图像更改之前添加了 window.URL.revokeObjectURL() 。还是不行。
我听说过 MediaSource() api,但我没有找到任何图像示例。这段代码有什么问题?
export default function ImageUploader({id, onAdd, onRemove}) {
const [preview, setPreview] = useState(null);
const onAddImage = (file: File) => {
window.URL.revokeObjectURL(preview);
setPreview(window.URL.createObjectURL(file));
onAdd(id, file);
};
const onRemoveImage = () => {
window.URL.revokeObjectURL(preview);
setPreview(null);
onRemove(id);
};
return (
<div>
{preview ? <Preview src={preview} alt={id} /> :
<Icon icon="upload" />
}
<input
type="file"
accept="image/png, image/jpeg"
onChange={(e) => onAddImage(e.target.files[0])}
/>
</div>
);
}
【问题讨论】:
-
你能展示你的预览组件吗?
-
只是一个img标签: const Preview = styled.img` object-fit: cover;边框半径:8px; `;问题不是从这里来的。我已经登录预览,我可以看到它在第一次上传后不再更新。
-
使用与您的代码相似的最少代码通过代码沙箱,这工作正常。 link
-
我已经用完整的代码更新了沙箱:codesandbox.io/s/red-tree-3kglr?file=/src/App.tsx 它在这里不起作用,当您拖放或多次单击“上传”时。
-
我做了一些更改。现在检查您的沙箱。您错过了使用 Preview 组件。 link
标签: reactjs input file-upload createobjecturl