如何在用户上传图像后立即在 React 应用程序的网站上显示图像?

How can I show an image in the website of a react application, right after a user uploads it?

场景是这样的:用户必须上传一个文件,一旦他上传了,我希望服务器一收到它就在页面上显示它。 我尝试了条件渲染,但它不起作用。

我应该怎么做才能让它发挥作用?提前致谢。

代码:

import React, { useState } from 'react'

import './App.css'

function App() {
  const [image, setImage] = useState('')

  const submitHandle = (e) => {
    if (!image) {
      console.log('please upload an image')
    } else {
      console.log(e.target)

      e.preventDefault()
      console.log('submitted')
    }
  }

  return (
    <section>
      <div>
        <div>
          <h1>heading one</h1>
          <form onSubmit={submitHandle}>
            <input
              value={image}
              onChange={(e) => setImage(e.target.value)}
              type='file'
              accept='image/gif, image/jpeg, image/png'
            />
            <button type='submit'>submit</button>
          </form>
          {image && <img src={image} alt='image' />}
        </div>
      </div>
    </section>
  )
}

export default App

对于 file 类型的 input,其值无法通过代码设置。

要立即查看图像,您必须使用 FileReader;

将其转换为字符串

因此我们必须创建另一个函数 loadImage 并将所选文件作为参数传入


完整代码

function App() {
  const [image, setImage] = useState('');
  
  const loadImage = (file) => {
    const reader = new FileReader();
    reader.addEventListener('load', e => setImage(e.target.result));
    reader.readAsDataURL(file);
  }

  const submitHandle = (e) => {
    if (!image) {
      console.log('please upload an image')
    } else {
      console.log(e.target)

      e.preventDefault()
      console.log('submiited')
    }
  }

  return (
    <section>
      <div>
        <div>
          <h1>heading one</h1>
          <form onSubmit={submitHandle}>
            <input
              onChange={(e) => loadImage(e.target.files[0])}
              type='file'
              accept='image/gif, image/jpeg, image/png'
            />
            <button type='submit'>submit</button>
          </form>
          {image && <img src={image} alt='image' />}
        </div>
      </div>
    </section>
  )
}