首页 > 解决方案 > 通过输入事件将图像加载到 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" />
    );
}

标签: reactjstypescript

解决方案


对于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>
  );
}

推荐阅读