简体   繁体   English

如何在 React 中悬停时定位特定的列表项?

[英]How can i target a specific item of list on hover in React?

I'm new in React.我是 React 的新手。 I want to show a div element when I hover one list item.当我悬停一个列表项时,我想显示一个 div 元素。 But now the change is happening on all of them.但现在变化正在发生在所有人身上。 I want the div to appear only on the hovered list item.我希望 div 只出现在悬停的列表项上。

This is the LabelList components which is the parent component of one list item.这是 LabelList 组件,它是一个列表项的父组件。

const LabelList = ({labelIcon, createFolderIcon}) => {


  const [isHover, setIsHover] = useState(false);

  const handleMouseEnter = (e) => {
    console.log(e.target)
    setIsHover(true);
    
  }

  const handleMouseOut = () => {
    setIsHover(false);
  };

  return (
    <ul className=' pl-3 pb-3 label-list'>
        <ListItem className='active ' icon={labelIcon} handleMouseOut={handleMouseOut} handleMouseEnter={handleMouseEnter} isHover={isHover}>
          <p>February</p>
          <div className="flex ml-auto mr-3"> 
            {isHover && (
              <EditDelete />
            )}</div>
        </ListItem>
        
        <ListItem icon={labelIcon} handleMouseOut={handleMouseOut} handleMouseEnter={handleMouseEnter} isHover={isHover}>
          <p>June</p>
        </ListItem>
        <ListItem icon={createFolderIcon}>
          <p style={{color:"#6F76A7;"}}>Create new label</p>
        </ListItem>
    </ul>
  )
}

This is the component for the single list item.这是单个列表项的组件。


  return (
    
    <li className={`list-item flex align-middle items-center mb-1 ${className}`} onMouseEnter={handleMouseEnter} onMouseOut={handleMouseOut}>
      
      <ListItemIcon icon={icon}/>
        {children}
    </li>
  )
}  ```

The problem is that you are using the same and only state 'isHover' for all the list items.问题是您对所有列表项使用相同且唯一的状态“isHover”。

This way, if you hover on one list item, isHover will be set to true, and all the other list items will start behaving as if you hovered on them too.这样,如果您将鼠标悬停在一个列表项上,isHover 将设置为 true,并且所有其他列表项将开始表现得好像您也将鼠标悬停在它们上一样。

What you should do is put the const[isHover, setIsHover] = useState(false) inside the ListItem component so that each list item can check for their own hover state.您应该做的是将const[isHover, setIsHover] = useState(false)放入 ListItem 组件中,以便每个列表项都可以检查自己的悬停状态。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM