首页 > 解决方案 > 反应元素事件

问题描述

因此,当用户将焦点/悬停在输入/按钮上时,我试图设置元素的样式。我这样做的方式是使用状态并将其设置为 true 或 false 如果用户悬停或聚焦但发现它非常重复并且需要大量代码,考虑到我必须创建一个聚焦和悬停状态对于每个按钮或输入。例如,我正在做:

 const [hoveredBtn, setHoveredBtn] = useState(false)
 const [themecolor, setThemecolor]=useState('red') //this state is being from firebase, red would 
  //just be an example, it can be whatever the user sets it to.
 return (
 <button 
 onMouseOver={()=>setHoveredBtn(true)} 
onMouseLeave={()=>setHoveredBtn(false)} 
style={hoveredBtn?{backgroundColor: themecolor}:{backgroundColor:"white"}}
 >
Button
 </button>
 )

因此,我需要为我拥有的每个按钮或输入创建一个悬停变量,并且我想知道是否有办法做到这一点,但是当我尝试时出现错误:

 return (
  <button onMouseOver={this.style.color=themecolor} onMouseLeave= 
 {this.style.color='white'}>Button</button>
  )

标签: reactjs

解决方案


您不能使用内联样式指定伪类。这意味着:hover, :focus, :active, 或:visited走出窗口而不是组件。来源:https ://www.freecodecamp.org/news/react-styled-components-inline-styles-3-other-css-styling-approaches-with-examples/

style.css

.myComponent:hover {
    // define style
}

myReactComponent.jsx

import './style.css';

推荐阅读