我正在尝试使用 React 更改悬停时 div 的背景颜色(但是,我不想为此创建一个全新的类)。我认识到我的语法不正确,但我找不到“正确”的方法来执行此操作。这是我的代码笔:
http://codepen.io/grapefruit0/pen/pRyOGG?editors=1010
在第 37-42 行,您将看到以下代码片段:
{
if (hover){
backgroundColor: "#b3ffff",
}else{
backgroundColor: "#b30000",
}
}
其中悬停定义如下:
getInitialState(){
return {hover: false};
}
mouseOver(){
this.setState({hover: true});
}
mouseOut(){
this.setState({hover: false});
}
有正确的方法吗?
最佳答案
您可以使用conditional (ternary) operator :
const boxStyle = {
margin: 5,
width: 30,
height: 30,
backgroundColor: this.state.hover ? "#b3ffff" : "#b30000",
display: "inline-block",
textAlign: "center"
}
但我认为在这种情况下最好的方法是仅使用 CSS 伪类 :hover
关于javascript - 在 React 的样式类中包含条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41617496/