在反应中添加红叉删除功能悬停

add red cross delete functionality onhover in react

所以我有来自 api 的数据并映射到它们上以呈现这些图像:

所以我正在尝试做这个项目,现在我基本上卡住了,我的反应不是很好 css 但我正在学习,我现在想做的是添加删除功能。我创建了一个功能,当我点击图片时,它会从数据中删除图片,但我想要的是,当我将鼠标悬停在图片上时,会出现一个红叉,当我按下红叉时,我可以触发该功能并删除图片

代码:

import React,{useState,useEffect,useReducer} from 'react';
import axios from 'axios';
import {useForm} from 'react-hook-form';

const Data = () => {

    const [photo,setPhoto] = useState([])

    useEffect(() => {
        axios.get("https://jsonplaceholder.typicode.com/photos").then(
            result => {
                setPhoto(result.data)
            }
        )
    },[])

    const [Url,setUrl] = useState()
    const[photoId,setPhotoId] = useState()

    const showPicture = (url,id) => {
        setUrl(url)
        setPhotoId(id)
    }


    const handleDelete = id => {
        setUrl(null);
        setPhoto(prevState => prevState.filter(x => x.id !== id));
      };

      const {register,handleSubmit,errors} = useForm();
      const [links,setLinks] = useState({
          link:'',
          thumbnailLink:'',
          title:''
        })

        const onSubmit = (data) => {
            console.log(data)
        };

    return(
        <div>
            <div><img src={Url} onClick={() => handleDelete(photoId)}></img></div>
            <div>Posts</div>
            {/* <p>enter album Id to see the magic</p><input type="text" value={albumId} onChange={e => setAlbumId(e.target.value)}></input>
            <button type="button" onClick={handleClick}>Fetch Album</button> */}
            <div className="container">
            <div>{photo.slice(0,3).map(p => 
                 <div key={p.id}>
                    <img src={p.thumbnailUrl} thumbnailUrl={p.thumbnailUrl} onClick={() => showPicture(p.url,p.id)}></img>
                        <div>{p.title}</div>
                </div>
            )}</div>
            </div>
                <form onSubmit={handleSubmit(onSubmit)}>
                    <input type="url" placeholder="link" name="link" ref={register}/>
                    <input type="url" placeholder="thumbnail url" name="thumbnail" ref={register}/>
                    <input type="text" placeholder="title" name="title" ref={register}/>
                    <input type="submit" />
                </form>
        </div>

    )
}

export default Data;

您需要做的就是在删除按钮上添加一个类名,默认情况下将其 css 设置为 display: none,悬停 属性 时只需将其设置为 display: unset 它应该像魔术一样工作。

我尝试将它应用到您的代码中。

我刚刚用 x 添加了一个 div 并使用了一个箭头函数,这样我就可以传递照片的 ID:

<div className='container-delete' onClick={e => this.handleDelete(p.id)}>X</div>

和 css 风格:

.container-delete {
 display: none;
 color: red;
}

.container-delete {
 display: unset;
}

这是完整的代码(只需在 css 文件中添加 css 用于隐藏和显示):

import React,{useState,useEffect,useReducer} from 'react';
import axios from 'axios';
import {useForm} from 'react-hook-form';

const Data = () => {

    const [photo,setPhoto] = useState([])

    useEffect(() => {
        axios.get("https://jsonplaceholder.typicode.com/photos").then(
            result => {
                setPhoto(result.data)
            }
        )
    },[])

    const [Url,setUrl] = useState()
    const[photoId,setPhotoId] = useState()

    const showPicture = (url,id) => {
        setUrl(url)
        setPhotoId(id)
    }


    const handleDelete = id => {
        setUrl(null);
        setPhoto(prevState => prevState.filter(x => x.id !== id));
      };

      const {register,handleSubmit,errors} = useForm();
      const [links,setLinks] = useState({
          link:'',
          thumbnailLink:'',
          title:''
        })

        const onSubmit = (data) => {
            console.log(data)
        };

    return(
        <div>
            <div><img src={Url} onClick={() => handleDelete(photoId)}></img></div>
            <div>Posts</div>
            {/* <p>enter album Id to see the magic</p><input type="text" value={albumId} onChange={e => setAlbumId(e.target.value)}></input>
            <button type="button" onClick={handleClick}>Fetch Album</button> */}
            <div className="container">
            <div>{photo.slice(0,3).map(p => 
                 <div key={p.id}>
                    <img src={p.thumbnailUrl} thumbnailUrl={p.thumbnailUrl} onClick={() => showPicture(p.url,p.id)}></img>
                    <div>{p.title}</div>
                    <div className='container-delete' onClick={e => this.handleDelete(p.id)}>X</div>
                </div>
            )}</div>
            </div>
                <form onSubmit={handleSubmit(onSubmit)}>
                    <input type="url" placeholder="link" name="link" ref={register}/>
                    <input type="url" placeholder="thumbnail url" name="thumbnail" ref={register}/>
                    <input type="text" placeholder="title" name="title" ref={register}/>
                    <input type="submit" />
                </form>
        </div>

    )
}

export default Data;

你可以看看这个

          {photo.slice(0, 3).map(p => (
            <div key={p.id} onClick={() => deleteIt(p)}>
              <img
                alt="theme"
                src={p.thumbnailUrl}
                thumbnailUrl={p.thumbnailUrl}
                onClick={() => showPicture(p.url, p.id)}
              />
              <div>{p.title}</div>
            </div>
          ))}

删除函数

  const deleteIt = item => {
    let filtered = photo.filter(p => p.id !== item.id);
    setPhoto(filtered);
  };

Live working demo

您可以在悬停具有属性 onMouseEnter

的 HTML 元素时调用方法

在您的组件中添加此属性:

<div key={p.id} onMouseEnter={() => displayRedLine(p.id)}>
  <img src={p.thumbnailUrl} thumbnailUrl={p.thumbnailUrl} onClick={() => showPicture(p.url,p.id)} onMouseen/>
  <p>{p.title}</p>
</div>

创建一个新状态以了解照片是否悬停:

const [photoHovered, setPhotoHovered] = useState(0) // It takes the id of hovered photo

displayRedLine(String id) 方法:

const displayRedLine = id => {
  setPhotoHovered(id); //It take the id of the photo when it was hovered

}

最后,显示一条红线,有条件知道它是否悬停感谢:
p.id === photoHovered ? /** make something **/

使用css :hover悬停时显示按钮。编写删除处理程序并将 index 传递给它并使用数组 splice 删除照片。

Working demo (hover & close functionality)

删除处理程序

const handleImageDelete = id => {
    const updatedPhotos = [...photo];
    updatedPhotos.splice(id, 1);
    setPhoto(updatedPhotos);
  };

JSX

<div>
      <div className="container">
        <div>
          {photo.slice(0, 3).map((p, i) => (
            <div className="image" key={p.id}>
              <img
                alt=""
                key={p.id}
                src={p.thumbnailUrl}
                thumbnailUrl={p.thumbnailUrl}
                onClick={() => showPicture(p.url, p.id)}
              />
              <div
                className="delete"
                type="button"
                onClick={() => handleImageDelete(i)}
              >
                X
              </div>
              <div>{p.title}</div>
            </div>
          ))}
        </div>
      </div>
    </div>

样式

.image {
  position: relative;
  width: 150px;
  margin: 0px auto;
}

.image .delete {
  background-color: red;
  width: 20px;
  padding: 10px;
  color: white;
  display: none;
  cursor: pointer;
  position: absolute;
  top: 0;
  right: 0;
}

.image:hover .delete {
  display: block;
}