You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React中使用useState实现hover切换类名时Show类不生效如何解决

问题原因

核心问题是useState返回值的使用逻辑错误:
React的useState返回值是长度为2的数组,第一个元素为当前存储的状态值,第二个为修改状态的方法。你的代码中命名逻辑和使用逻辑混乱:

const [hover, isHover] = useState(false);
// 此处hover是布尔类型的状态值,isHover是修改状态的函数
const showIcons = isHover ? "Show" : "";
// 你错误将函数类型的isHover作为判断条件,函数属于真值,无论状态怎么切换,判断结果永远为真,要么类名永远存在要么和你的预期逻辑完全相反,看起来就是Show类没有生效
修复方案
  1. 修正类名判断逻辑,使用真实的状态变量做判断,建议调整更新函数的命名为set开头的通用规范,避免后续再出现混淆
  2. 可以给.Info添加过渡属性,实现你预期的opacity平滑过渡效果

修正后的组件代码

import React,{useState} from 'react';
import './MyWork.css';
import {Visibility, GitHub } from "@material-ui/icons";


const SingleProject = ({src, title}) => {
    const [isHover, setIsHover] = useState(false);
    const showIcons = isHover ? "Show" : "";

    return (
        <div className="card-container" onMouseEnter={()=> setIsHover(true)} onMouseLeave={()=> setIsHover(false)}>
            <img src={src} alt={title}/>
            <h1 id="card-title">{title}</h1>
           <div className={`Info ${showIcons}`}>
                <div className="Icon">
                    <GitHub/>
                </div>
                <div className="Icon">
                    <Visibility/>
                </div>
            </div>
        </div>
    )
}

export default SingleProject;

修正后的CSS代码(新增过渡效果)

.card-container {
    height: 314px;
    width: 500px;
    cursor: pointer;
    position : relative;
}
.Info {
    position: absolute;
    height: 100%;
    width: 100%;
    top:0;
    left:0;
    display:flex;
    justify-content:center;
    align-items: center;
    background-color: rgba(0, 0, 0, 0.5);
    opacity: 0;
    transition: opacity 0.3s ease; /* 新增过渡属性,实现平滑切换 */
}

.Info.Show {
    opacity: 1;
}

内容的提问来源于stack exchange,提问作者TheRealJohnDoe

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 07:45:04