多张图片已上传但未显示在 UI (React Js)

Multiple images have uploaded but not showing in UI (React Js)

我正在尝试使用 React js 上传图片,但我无法同时上传多张图片,即使我输入的是多张图片。

<input type="file" title="" className={styles.inputFile} multiple={true} onChange={handleChange} />

 const [formData, setFormData] = useState({
    orgId: "6114285831310bfd5b09c28178e",
    orgWallpaper: [],
  }); 

const handleChange = (e) => {
    if (e.target.files && e.target.files[0]) {
      setFormData((form) => ({
        ...form,
        orgWallpaper: [...form.orgWallpaper, URL.createObjectURL(e.target.files[0])],
      }));
    }
  };

{formData?.orgWallpaper?.map((item, key) => (
                  {console.log(item, "mapitem")}
                  <img className={styles.wallpapers + " " + styles.active} src={item} alt="" />

您可以检查一下:

...(e.target.files?.map(file=>URL.createObjectURL(file))??[])

并删除控制台日志,它实际上破坏了 return 语法。如果你想检查 console.log 然后也写一个 return :

 {formData?.orgWallpaper?.map((item, key) => ( <img key={key} className={styles.wallpapers + " " + styles.active} src={item} alt="" />)
    }

您应该像下面这样更改 handleChange

const {useState} = React;

const MultipleFilesUpload = () => {
  const [formData, setFormData] = useState({
    orgId: "6114285831310bfd5b09c28178e",
    orgWallpaper: [],
  });

  const handleChange = (e) => {
    var files = e.target.files;
   for (let i = 0; i <files.length; i++) {
   setFormData((form) => ({
        ...form,
        orgWallpaper: [...form.orgWallpaper, URL.createObjectURL(files[i])]})
        )}};
        
  return ( 
  <div>
      <input type="file" title="" multiple onChange={handleChange}/> 
      <div class="gallery">
      {
      formData.orgWallpaper.map((item, key) =>
        <img width ="48px" src ={item} alt= "" />
      )} 
      </div> 
   </div>
)};

ReactDOM.render( <MultipleFilesUpload/> ,
  document.getElementById("root")
);
.gallery {
  display: flex;
}

.gallery img {
  margin: 10px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.1/umd/react-dom.production.min.js"></script>
<div id="root"></div>