gpt4 book ai didi

javascript - React JS 在悬停时切换/添加类

转载 作者:可可西里 更新时间:2023-11-01 02:51:32 25 4
gpt4 key购买 nike

我将 animate.css 库与 React 一起使用,并尝试设置一个元素(按钮)在鼠标悬停时发出脉冲。试图查看文档和此处,但找不到实现此简单任务的方法。如果有人实现了这一目标或找到了引用,我们将不胜感激。

class App extends Component {

constructor(props) {
super(props);

this.handleHover = this.handleHover.bind(this);
}

handleHover(){
this.setState({
isHovered: !this.state.isHovered
});
}

render() {
const btnClass = this.state.isHovered ? "pulse animated" : "";

return (
<div>
<button className={btnClass} onMouseEnter={this.state.handleHover} onMouseLeave={this.state.handleHover}>Test</button>
</div>
);
}
}

export default App;

最佳答案

您可以在组件上使用 onMouseEnteronMouseLeave 事件并相应地切换类。

constructor(){
super();
this.state = {
isHovered: false
};
this.handleHover = this.handleHover.bind(this);
}
handleHover(){
this.setState(prevState => ({
isHovered: !prevState.isHovered
}));
}
render(){
const btnClass = this.state.isHovered ? "pulse animated" : "";
return <button className={btnClass} onMouseEnter={this.handleHover} onMouseLeave={this.handleHover}></button>
}

2019 年 5 月 7 日更新: Hook

import React, { useState } from 'react';

export default function Component () {
const [hovered, setHovered] = useState(false);
const toggleHover = () => setHovered(!hovered);
return (
<button
className={hovered ? 'pulse animated' : ''}
onMouseEnter={toggleHover}
onMouseLeave={toggleHover}
>
</button>
)
}

关于javascript - React JS 在悬停时切换/添加类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44575727/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com