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]
  );
已标记关键词 清除标记
相关推荐
©️2020 CSDN 皮肤主题: 撸撸猫 设计师:C马雯娟 返回首页