react列表元素hover

常见的列表元素hover,我们使用的方式是,在获得原始数组对象的时候加一个标识符,然后mouseIn 的时候改变状态,mouseOut的时候恢复状态;
在这里插入图片描述

一、举例演示

const arr = [
  {name:'123',age:13,sex:'man'},
  {name:'125',age:13,sex:'man'},
  {name:'124',age:13,sex:'man'}
 ]

(1)添加标识

const arr = [
  {name:'123',age:13,sex:'man',show:false},
  {name:'125',age:13,sex:'man',show:false},
  {name:'124',age:13,sex:'man',show:false}
 ]

(2)hover某个元素时候改变状态(例如第一个)

const arr = [
  {name:'123',age:13,sex:'man',show:true},
  {name:'125',age:13,sex:'man',show:false},
  {name:'124',age:13,sex:'man',show:false}
 ]

(3)hover离开元素的时候,恢复状态;

const arr = [
  {name:'123',age:13,sex:'man',show:false},
  {name:'125',age:13,sex:'man',show:false},
  {name:'124',age:13,sex:'man',show:false}
 ]

二、react演示

鼠标进入离开

    list.map((item, index) => (
        <div
          className="normal"
          key={index}
          onMouseEnter={() => {
            handleMouseEnter(item.index);
          }}
          onMouseLeave={() => {
            handleMouseLeave(item.index);
          }}
        >
          {item.name}
        </div>)
  );

js进行数据操作

  import { useState,useCallback } from 'react';
  const [list, setList] = useState([]);
  setList( [
   {name:'123',age:13,sex:'man',show:false},
   {name:'125',age:13,sex:'man',show:false},
   {name:'124',age:13,sex:'man',show:false}
  ]);


// 因为是要修改useState处理后的值,所有需要使用useCallback来处理,其他要进行一次浅拷贝
  const handleMouseEnter = useCallback(
    (index) => {
      const copy = list.concat();
      const target = list[index];
      target.show = true;
      copy[index] = target;
      setList(copy);
    },
    [list]
  );
// 因为是要修改useState处理后的值,所有需要使用useCallback来处理,其他要进行一次浅拷贝
  const handleMouseLeave = useCallback(
    (index) => {
      const copy = list.concat();
      const target = list[index];
      target.show = false;
      copy[index] = target;
      setList(copy);
    },
    [list]
  );
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值