react实现表格滚动
1、js组件
import React from 'react';
import styles from './TableRolling.module.scss'
class TableRolling extends React.Component {
constructor(props) {
super(props);
}
componentDidMount = () => {
this.industryNews = setInterval(this.taskIndustryNews, 50);
}
// 表格数据滚动
taskIndustryNews = () => {
if (this.refs.newDiv.scrollTop >= this.refs.newDivUI.offsetHeight - this.refs.newDiv.clientHeight) {
this.refs.newDiv.scrollTop = 0;
}
else {
this.refs.newDiv.scrollTop += 1;
}
}
handleIndustryNewsEnter = () => {
clearInterval(this.industryNews);
}
handleIndustryNewsLeave = () => {
this.industryNews = setInterval(this.taskIndustryNews, 100);
}
componentWillUnmount = () => {
clearInterval(this.industryNews);
}
render() {
return (
<div className={styles.Table}>
<div className={styles.tableTitle}>
{
this.props.data.columns.map((item,index)=>{
return(
<span className={styles.tableText2}>{item}</span>
)
})
}
</div>
<div
ref='newDiv'
className={styles.tableBody}
onMouseEnter={this.handleIndustryNewsEnter.bind(this)}
onMouseLeave={this.handleIndustryNewsLeave.bind(this)}
>
<ul ref='newDivUI'>
{this.props.data && this.props.data.dataSource && this.props.data.dataSource.length > 0
?
this.props.data.dataSource.map(this.tableBody)
: <span className={styles.noData}>暂无数据</span>
}
</ul>
</div>
</div>
);
}
// 添加表格内容
tableBody = (item, index) => {
return (
<li key={index}>
{
// 遍历数据,增加标红处理
Object.values(item).map((i,index) => {
const currentColor = (index == 1 && i > 30) || (index == 3 && i > 40) ? '#FF0000' : 'rgba(255, 255, 255, 0.8)'
return(
<span className={styles.tableText2} key={index} style={{color:currentColor}}>
{i}
</span>
)
})
}
</li>
);
}
}
export default TableRolling;
2、样式scss
.Table {
text-align: center;
font-size: 14px;
height: 100%;
.tableText2 {
width: 20%;
display: inline-block;
}
.tableTitle {
color: rgba(255, 255, 255, 0.8);
background: rgba(96, 183, 200, 0.3);
padding:3% 1%;
display: flex;
align-items: center;
justify-content: space-around;
}
.tableBody {
height: calc(95% - 30px);
overflow-y: scroll;
color: rgba(255, 255, 255, 0.8);
ul {
padding-inline-start: 0px;
.noData {
height: 78px;
line-height: 78px;
}
li {
background: transparent;
display: flex;
align-items: center;
justify-content: space-around;
min-height: 24px;
padding:2% 0;
span {
font-size: 12px;
}
}
li:nth-child(2n) {
background:rgba(96, 183, 200, 0.1);
}
li:hover {
background-color: rgba(96, 183, 200, 0.5);
}
}
&::-webkit-scrollbar {
width: 3px;
}
&::-webkit-scrollbar-thumb {
background: rgba(0, 180, 251, 0.5);
border-radius: 7px;
box-shadow: inset 0 0 15px rgba(0, 180, 251, 1);
}
}
}
3、使用
import TableRolling from './TableRolling'
// ...
<TableRolling data={TableList}/>
4、传入的数据格式
不同数据格式修改下循环就可
const TableList = {
columns : ['xxx','xxx','xxxx'], // 表头名称
dataSource : [ // 数组
{
name1:'001',
name2:'16',
name3:'24',
name4:'41'
},
{
name1:'002',
name2:'16',
name3:'24',
name4:'41'
},
]
}