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

React中如何实现按钮按下变白、松开恢复黑色的交互效果?

解决方案

你需要监听鼠标的按下(onMouseDown)和松开(onMouseUp、onMouseLeave)事件,而非点击事件,来实现“按下变白色、松开恢复黑色”的效果:

import { useState } from 'react';

function PressableButton() {
  const [isPressed, setIsPressed] = useState(false);

  return (
    <button
      style={{
        backgroundColor: isPressed ? 'white' : 'black',
        color: isPressed ? 'black' : 'white', // 可选:切换文字颜色提升可读性
        padding: '8px 16px',
        border: 'none',
        cursor: 'pointer'
      }}
      onMouseDown={() => setIsPressed(true)}
      onMouseUp={() => setIsPressed(false)}
      onMouseLeave={() => setIsPressed(false)} // 处理鼠标移出按钮但未松开的情况
    >
      点击我
    </button>
  );
}

export default PressableButton;

关键说明:

  • onMouseDown:鼠标按下按钮时触发,将状态设为true,按钮背景切换为白色
  • onMouseUp:鼠标松开时触发,将状态设为false,按钮恢复黑色
  • onMouseLeave:避免用户按下按钮后,鼠标移出按钮区域再松开时,按钮无法恢复初始颜色的问题
  • 初始状态isPressed设为false,对应按钮默认显示黑色

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 06:29:54