Reactjs 通过输入事件将图像加载到img中
查询的原因是我无法显示加载到标记中的图像: 对于输入事件,执行handleChange函数,在该函数中确认事件是与照片编号1对应的事件,因此为if(fieldName==“photo1”)。但图像永远不会显示。事实上,在照片1中,我得到了图像的名称和形状 如何显示图像?o我做错了什么Reactjs 通过输入事件将图像加载到img中,reactjs,typescript,Reactjs,Typescript,查询的原因是我无法显示加载到标记中的图像: 对于输入事件,执行handleChange函数,在该函数中确认事件是与照片编号1对应的事件,因此为if(fieldName==“photo1”)。但图像永远不会显示。事实上,在照片1中,我得到了图像的名称和形状 如何显示图像?o我做错了什么 const SetItem = () =>{ const [foto1,setFoto1]=useState<string>("-"); const han
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" />
);
}
const SetItem=()=>{
const[foto1,setFoto1]=useState(“-”);
const handleChange=(字段名:字符串)=>(e:any)=>{
如果(字段名==“foto1”){
setFoto1(e.currentTarget.files[0].name);
设img=document.getElementById(“imagen1”);
(img!作为HTMLImageElement).src=foto1!;
}
};
返回(
);
}
尝试使用此函数将图像转换为base64字符串
然后将src设置为base64字符串
constfiletobase64=(文件)=>
新承诺((解决、拒绝)=>{
const reader=new FileReader();
reader.readAsDataURL(文件);
reader.onload=()=>resolve(reader.result);
reader.onerror=(错误)=>拒绝(错误);
});
尝试使用此函数将图像转换为base64字符串
然后将src设置为base64字符串
constfiletobase64=(文件)=>
新承诺((解决、拒绝)=>{
const reader=new FileReader();
reader.readAsDataURL(文件);
reader.onload=()=>resolve(reader.result);
reader.onerror=(错误)=>拒绝(错误);
});
对于img
标记,我们需要一个图像路径(相对/绝对),而不是文件名
否则,我们可以使用浏览器FileReader
API读取文件,并以datauri
格式显示图像
你能查一下下面的地图吗
import React,{useState}来自“React”;
导出默认函数App(){
const[image,setImage]=useState(“”);
常量handleChange=(文件)=>{
常量输入=file.currentTarget;
var reader=new FileReader();
reader.onload=函数(){
const dataURL=reader.result;
setImage({name:input.files[0].name,src:dataURL});
};
reader.readAsDataURL(input.files[0]);
};
返回(
);
}
对于img
标记,我们需要一个图像路径(相对/绝对),而不是文件名
否则,我们可以使用浏览器FileReader
API读取文件,并以datauri
格式显示图像
你能查一下下面的地图吗
import React,{useState}来自“React”;
导出默认函数App(){
const[image,setImage]=useState(“”);
常量handleChange=(文件)=>{
常量输入=file.currentTarget;
var reader=new FileReader();
reader.onload=函数(){
const dataURL=reader.result;
setImage({name:input.files[0].name,src:dataURL});
};
reader.readAsDataURL(input.files[0]);
};
返回(
);
}
谢谢。我在setImage:Argument类型{name:any;src:string | ArrayBuffer | null;}上得到的结果是,不能将其赋值给SetStateAction类型的参数。Object literal只能指定已知的属性,并且type'(prevState:string)=>StringThank中不存在“name”。我只是用钩子图像来存储路径,而不是用图像名来解决这个问题谢谢。我在setImage:Argument类型{name:any;src:string | ArrayBuffer | null;}上得到的结果是,不能将其赋值给SetStateAction类型的参数。Object literal只能指定已知的属性,并且type'(prevState:string)=>StringThank中不存在“name”。我只是使用钩子图像来存储路径,而不是图像名称来解决这个问题