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
相关产品推荐
相关产品推荐

