reactjs - 通过输入事件将图像加载到 img
问题描述
查询的原因是因为我无法显示标签中加载的图像:
使用输入事件,执行handleChange函数,在其中确认事件是对应于照片编号1的事件,因此是if (fieldName == "photo1")。但是图像永远不会显示。事实上,在 photo1 中,我得到了图像的名称及其形状。
怎么可能显示图像?o 我做错了什么?
const SetItem = () =>{
const [foto1,setFoto1]=useState<string>("-");
const handleChange = (fieldName: string) => (e:any) => {
if(fieldName=="foto1"){
setFoto1(e.currentTarget.files[0].name);
let img=document.getElementById("imagen1");
(img! as HTMLImageElement).src=foto1!;
}
};
return(
<input id="inputFile1" type="file" accept="image/*" onChange={ handleChange("foto1")} />
<img id="imagen1" src={foto1} alt="your image" />
);
}
解决方案
对于img
标签,我们需要一个图像路径(相对/绝对),而不是文件名。
FileReader
否则我们可以使用浏览器API读取文件并以data uri
格式显示图像。
你能检查下面的例子吗
import React, { useState } from "react";
export default function App() {
const [image, setImage] = useState("");
const handleChange = (file) => {
const input = file.currentTarget;
var reader = new FileReader();
reader.onload = function () {
const dataURL = reader.result;
setImage({ name: input.files[0].name, src: dataURL });
};
reader.readAsDataURL(input.files[0]);
};
return (
<div className="App">
<input
id="inputFile1"
type="file"
accept="image/*"
onChange={handleChange}
/>
<img id="imagen1" src={image.src} alt="your" />
</div>
);
}
推荐阅读
- python - 如何暂停 Jupyter Notebook 小部件,等待用户输入
- pyspark - Pyspark over zeppilin:无法导出为 csv 格式?
- ruby-on-rails - 在rails中将字符串转换为整数
- android - 获取根目录内容
- javascript - 如何用参数模拟点击按钮
- c# - 检查用户在 radgridview 的过滤器列中输入了什么
- validation - 如何在 Angular 6 表单控件验证器中一次仅显示一个验证
- c# - 来自组 SpecialServiceRQ 的意外 ERR.SWS.CLIENT.VALIDATION_FAILED
- python - pyusb/libusb0 Windows 权限不足
- eclipse - org.hibernate.TransactionException:事务超时已过期