Javascript React JS 切换/在悬停时添加一个类
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/44575727/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
React JS toggle/ adding a class on hover
提问by Fernando B
I'm using the animate.css library with React and trying to set up a element (button) to pulse when hovered over. Tried to look through the docs and here but can't find a way to achieve this simple task. If anyone has achieved this or found a reference would greatly be appreciated.
我正在将 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;
回答by Chase DeAnda
You can use the onMouseEnterand onMouseLeaveevents on the component and toggle the class accordingly.
您可以在组件上使用onMouseEnter和onMouseLeave事件并相应地切换类。
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>
}
Update 05/07/19: Hooks
19 年 7 月 5 日更新:挂钩
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>
)
}

