css - 如何使用 React 更改选定的表格行背景颜色
问题描述
我想在单击时更改表格行背景颜色,并在单击另一行时更改为原来的颜色。
我试过这样的事情:
index.js
state = {
color: []
}
render(){
return (
<Table>
<thead>
<tr>
<th>name</th>
<th>age</th>
<th>address</th>
</tr>
</thead>
<tbody className="tableHover">
{this.props.students.map((item, i) => {
return (
<tr key={i} onClick={this.changeColor(i)}>
<td>{item.name}</td>
<td>{item.age}</td>
<td>{item.address}</td>
</tr>
);
})}
</tbody>
</Table>
);
changeColor = (selectedRow) => e => {
if (selectedRow){
this.setState({color: 'blue'})
}
}
}
样式.css
.tableHover :hover {
color: white;
background-color: blue;
}
提前致谢!
解决方案
selectedRow
您可以在其中维护一个state
并根据匹配索引向该行添加一个类名。
className={this.state.selectedRow === i ? "tableSelected" : "" }
下面的完整工作代码
class App extends React.Component {
state = {
selectedRow: -1
};
render() {
return (
<table>
<thead>
<tr>
<th>name</th>
<th>age</th>
<th>address</th>
</tr>
</thead>
<tbody className="tableHover">
{this.props.students.map((item, i) => {
return (
<tr key={i} onClick={this.changeColor(i)} className={this.state.selectedRow === i ? "tableSelected" : "" }>
<td>{item.name}</td>
<td>{item.age}</td>
<td>{item.address}</td>
</tr>
);
})}
</tbody>
</table>
);
}
changeColor = selectedRow => e => {
if (selectedRow !== undefined) {
this.setState({ selectedRow });
}
};
}
ReactDOM.render(<App students={[{name: "a"}, {name: "b"}]}/>, document.getElementById("app"));
.tableHover :hover {
color: white;
background-color: blue;
}
.tableSelected {
background-color: blue;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="app"></div>
推荐阅读
- linux - 无法在 amazon linux AMI 上构建 rgdal 包
- reactjs - React Antd Design Checkbox.Group 默认选中不会发生?
- javascript - 当我使用 jQuery 附加工具提示元素时,引导工具提示不起作用
- java - 如何将 fxml 加载器的位置设置为另一个包中的 fxml
- android - 我的应用从一项活动转到另一项活动需要很长时间
- batch-file - 将 sharepoint 文档同步到 onedrive,而无需单击 sharepoint 本身上的“同步”按钮
- node.js - 服务器端 Node JS 应用程序和 Oauth2 同意页面
- java - 从 OpenShift Java REST 客户端重新启动 Pod
- excel - 具有多个系列的 Microsoft Excel 2010 堆积条形图
- python - 如何将高斯滤波器应用于 Python 的原始音频文件?