尝试在上传前预览图像

Sah*_*ata 0 html reactjs

我正在尝试渲染用户在页面上输入文件类型的图像,因此用户将在提交和上传图像之前预览图像,但我无法获取其值。

我一直试图做的是使用输入的值作为<img />组件的来源:

import React, { useState } from "react";

export default function Test() {
  const [image, setImage] = useState(null);
  return (
    <div>
   <form  onSubmit={() => {
      //Sumbit
    }}/>
    <input
      type="file"
      onChange={(e) => setImage(e.target.value)}
    ></input>
    {image ? <img src={image} /> : null}
    <button type={"submit"}></button>
  </form>
    </div>
  );
}
Run Code Online (Sandbox Code Playgroud)

但它总是返回一个值 - C:\fakepath\IMGName。有什么方法可以获取图像的值,以便将其渲染为图像?

小智 5

export default function App() {
  const [img, setImg] = useState(null);

  const handleImg = (e) => {
    setImg(URL.createObjectURL(e.target.files[0]));
  }

  return (
    <div className="App">
      <input type="file" onChange={handleImg} />
      <img src={img}/> 
    </div>
  );
}
Run Code Online (Sandbox Code Playgroud)