【问题标题】:In array map iterator, how to get value concatenate state and array map id在数组映射迭代器中,如何获取值连接状态和数组映射 id
【发布时间】:2019-11-11 13:22:33
【问题描述】:

我从服务器获取了几张图片,然后我使用数组映射助手以及文件输入来渲染它们以上传图片。 当我选择一个文件时,我想用实际的图像替换它。

我已经初始化了一个状态存储所选图像并设置值 onChage 事件。在 jsx 中,我根据状态值在三元运算符中设置图像 url。

  function App() { 
  const [photos, setPhotos] = useState(null);
  const [upload, setUpload] = useState(null);

  useEffect(() => {
    fetch('https://jsonplaceholder.typicode.com/photos?_start=0&_limit=2')
  .then(response => response.json())
  .then(json => setPhotos(json))
  }, [])

  const handleChange = e => {
    setUpload({...upload, [e.currentTarget.name]: URL.createObjectURL(e.currentTarget.files[0])});  
  };

  return (
    <div className="App">
      { photos ? photos.map(photo => (
          <div key={photo.id}>
            <div>
                {upload ? <img src={upload.photo_+photo.id} alt="" /> : <img src={photo.thumbnailUrl} alt="" /> }
            </div>
              <input type="file" name={`photo_${photo.id}`} onChange={handleChange} /><br /><br />
          </div>
        )) : <div>Loading...</div>
       }
    </div>
  );
}

当我选择一个图像时,什么都没有发生,应该替换实际的图像。

【问题讨论】:

标签: reactjs


【解决方案1】:

你需要使用

upload['photo_' + photo.id]

我也会用这个

{photos ? photos.map(photo => <Child photo={photo} key={photo.id} />) : <div>Loading...</div>}

所以最终应用应该是这样的

import React, { useState, useEffect } from "react";

export default function App() {
  const [photos, setPhotos] = useState(null);
  useEffect(() => {
    fetch("https://jsonplaceholder.typicode.com/photos?_start=0&_limit=2")
      .then(response => response.json())
      .then(json => setPhotos(json));
  }, []);

  return (
    <div className="App">
      {photos ? photos.map(photo => <Child photo={photo} key={photo.id} />) : <div>Loading...</div>}
    </div>
  );
}

const Child = ({ photo }) => {
  const [upload, setUpload] = useState(null);
  const handleChange = e => {
    setUpload(URL.createObjectURL(e.currentTarget.files[0]));
  };

  return (
    <div>
      <div>
        {upload ? (
          <img src={upload} alt="" />
        ) : (
          <img src={photo.thumbnailUrl} alt="" />
        )}
      </div>
      <input
        type="file"
        onChange={handleChange}
      />
      <br />
      <br />
    </div>
  );
};

【讨论】:

  • 非常感谢 Eugene Glova,它正在工作。
猜你喜欢
  • 2016-04-10
  • 2020-02-22
  • 2021-07-17
  • 1970-01-01
  • 2020-04-22
  • 1970-01-01
  • 2016-09-19
  • 2015-05-26
相关资源
最近更新 更多