Javascript 使用React在hover和onClick上为表行着色
当Javascript 使用React在hover和onClick上为表行着色,javascript,reactjs,react-native,onclick,onhover,Javascript,Reactjs,React Native,Onclick,Onhover,当onHover和onClick事件通过js和css发生时,我一直在尝试给我的表上色,但我对这两个都有相同的问题。。如果光标离开,激活的颜色将立即恢复为旧颜色 我想做的是,当您单击表中的行时,它将保持活动状态,直到单击另一行 对于css解决方案,我使用的是: .hoverClass:hover { background: red; } .hoverClass:active { background: yellow; } 对于js解决方案: onTableRowClicked = (
onHover
和onClick
事件通过js
和css
发生时,我一直在尝试给我的表上色,但我对这两个都有相同的问题。。如果光标离开
,激活的颜色将立即恢复为旧颜色
我想做的是,当您单击表中的行
时,它将保持活动状态,直到单击另一行
对于css解决方案,我使用的是:
.hoverClass:hover {
background: red;
}
.hoverClass:active {
background: yellow;
}
对于js解决方案:
onTableRowClicked = (e) => {
this.setState({ currentColoringTarget: e });
e.currentTarget.style.background = "#EEE55E";
};
changeTableRowBackgroundOnMouseOver = (e) => {
e.currentTarget.style.background = "#EEEEEE";
};
changeTableRowBackgroundOnMouseOut = (e) => {
e.currentTarget.style.background = "transparent";
};
...
<tbody
onClick={(e) => this.onTableRowClicked(e)}
onMouseOver={this.changeTableRowBackgroundOnMouseOver}
onMouseOut={this.changeTableRowBackgroundOnMouseOut}
>
<tr>
<th className="vertically-aligned-th">
<strong>1)</strong>
</th>
<th className="vertically-aligned-th">21314</th>
<th className="vertically-aligned-th">address2</th>
<th>
<Button className="acceptButton">Accept</Button>
</th>
<th>
<Button className="declineButton">Decline</Button>
</th>
</tr>
</tbody>
...
onTableRowClicked=(e)=>{
this.setState({currentColoringTarget:e});
e、 currentTarget.style.background=“#EEE55E”;
};
changeTableRowBackgroundOnMouseOver=(e)=>{
e、 currentTarget.style.background=“#EEEEEE”;
};
changeTableRowBackgroundOnMouseOut=(e)=>{
e、 currentTarget.style.background=“透明”;
};
...
this.ontablerow(e)}
onMouseOver={this.changeTableRowBackgroundOnMouseOver}
onMouseOut={this.changeTableRowBackgroundOnMouseOut}
>
1)
21314
地址2
接受
减少
...
下面是代码的示例。您的方向是正确的,但不是通过样式直接接触DOM。backgroundColor
您可以使用一些React状态跟踪行的ID,然后应用处理样式设置的选定类
我已经更新了沙箱,让您知道如何做到这一点
注意:我只对顶部表格的前两行应用了行选择。这个解决方案需要干燥,但应该会给你一个实现它的方法。用你的方法得到了它。。我甚至没有考虑过id
方法,但谢谢你。