反应:按X按钮从屏幕上删除图像

时间:2020-10-09 09:36:52

标签: reactjs react-hooks

我是React的入门者,我有一个应用程序可以从API返回一些图片。如果用户单击 col > 1 0 Personals 1 Financials 2 Data related to sexual preferences, sex life,... 3 Personals 4 Financials 5 Vendors 6 Procurement, subcontracting and vendor manage... ,我在每个图片上插入了'X'来删除图片。但是我不知道如何使用React Hooks删除特定的图像。

我的代码:

'X'

更新:使用下面的代码,我使用钩子从列表中删除了图像,但这些图像并未从图片中删除:

function City(){

  // custom func that returns the pics from the api and the loading state of my app 
  const {loading , pics  ,query , setQuery}  = useFetch('nature');
  
  //I believe I need something like this but have no idea how to use it (initial state is all 
  my pics and deleteImage must delete a single pic)
   
  const [images,deleteImage] =  useState(pics);
  
  return (<div className="city-info">
    {   
      //if app is loading display loading else return all pics  
       !loading ? 
        (pics.length>0 && pics.map((pic) =>{
          return  <div className="info" key = {pic.id}>
                    <span className="close">
                       //I want to use onClick on this button to delete the specific image 
                      <span  className="inner-x">
                        &times;
                      </span>
                    </span>
                    <img src = {pic.src.original} alt ="img"/> 
                  </div>
        })
       
       ):<div> Loading </div>

    }
  </div>);
}

1 个答案:

答案 0 :(得分:1)

所以这是一个有关如何删除数组内部项目的简单本地状态示例

import React, { useState, useEffect } from "react";
import "./styles.css";

const allImages = [
  {
    id: 1,
    imgUrl: "https://via.placeholder.com/100"
  },
  {
    id: 2,
    imgUrl: "https://via.placeholder.com/100"
  },
  {
    id: 3,
    imgUrl: "https://via.placeholder.com/100"
  }
];

const App = () => {
  const [pics, setPics] = useState([]);

  const removeImage = (id) => {
    // this is the line that you are looking for
    setPics((oldState) => oldState.filter((item) => item.id !== id));
  };

  useEffect(() => {
    //fake fetch data
    setPics(allImages);
  }, []);
  return (
    <div className="App">
      {pics.map((pic) => {
        return (
          <div style={{ marginBottom: "100px" }}>
            {pic.id}
            <img
              src={pic.imgUrl}
              width="100px"
              height="100px"
              alt="placeholder grey 100px"
            />
            <button onClick={() => removeImage(pic.id)}>X</button>
          </div>
        );
      })}
    </div>
  );
};

export default App;

sandbox link