【发布时间】:2017-10-31 22:45:08
【问题描述】:
我正在将一些数据加载到我的React 组件中的table 中。我正在使用来自materialize CSS framework 的表格显示数据。我可以看到表格中的数据。我正在使用来自 W3school.com 的table sort function。当我单击header 调用sortTable function 时,我收到一个错误消息TypeError: Table is null。产生错误的行是rows = table.getElementsByTagName('TR');。尽管我可以看到表格中的数据,但我不明白为什么会出现此错误?我的代码如下所示:
import React, { Component } from 'react';
class newsList extends Component {
constructor(props) {
super(props)
window.info = [];
}
render() {
this.props.arr.result ? window.info.push(this.props.arr.result) : null
var result = window.info.map(item => (
<tbody key={item.id}>
<tr>
<td>{item.profileInfo.profileName}</td>
<td>{item.rows[0][0]}</td>
<td>{item.rows[0][1]}</td>
<td>{item.rows[0][2]}</td>
<td>
<a href="#!" className="secondary-content">
<i className="material-icons">
send
</i>
</a>
</td>
</tr>
</tbody>))
//Sort function starts here.
const sortTable = (n) => {
console.log(window.info);
var table, rows, switching, i, x, y, shouldSwitch, dir, switchCount = 0;
table = document.getElementById('#dataTable');
console.log(table);
switching = true;
//Sort the sorting direction to ascending:
dir = 'asc';
//Make a loop that will continue until no switching has been done:
while (switching) {
//Start by saying: no switching is done:
switching = false;
rows = table.getElementsByTagName('TR');
//Loop through all table rows except the headers:
for (i = 1; i < (rows.length - 1); i++) {
//Start by saying there should be no switching:
shouldSwitch = false;
//Compare the two elements:
x = rows[i].getElementsByTagName('TD')[n];
y = rows[i].getElementsByTagName('TD')[n];
//Switch the rows:
if (dir === 'asc') {
if (x.innerHTML.toLowerCase() > y.innerHTML.toLowerCase()) {
shouldSwitch = true;
break;
}
} else if (dir === 'desc') {
if (x.innerHTML.toLowerCase() < y.innerHTML.toLowerCase()) {
shouldSwitch = true;
break;
}
}
}
if (shouldSwitch) {
//If a switch has been done marked, make the switch and mark that a switch has been done:
rows[i].parentNode.insertBefore(rows[i + 1], rows[i]);
switching = true;
//Each time a switch is done, increase this count by 1:
switchCount++;
} else {
//If no Switching has been done AND the direction is 'asc' set the direction to 'desc' and run the while loop again.
if (switchCount === 0 && dir === 'asc') {
dir = 'desc';
switching = true;
}
}
}
}
return (
<div>
<table id="dataTable" className="responsive-table">
<thead>
<tr>
<th onClick={() => sortTable(0)}>Account Name</th>
<th>Sessions</th>
<th>Bounces</th>
<th>Users</th>
</tr>
</thead>
{result}
</table>
</div>
)
}
}
export default newsList;
【问题讨论】:
-
table为空,因为document.getElementId不需要#符号来表示您正在寻找一个ID,它已经知道它是由于您使用的方法,只是寻找document.getElementById('dataTable')。也就是说,将 React 与 DOM 操作混合是一个糟糕的主意 -
@Icepickle 是的,我知道这是一个糟糕的主意,但我很难理解 React 文档中的
setState,而且我不知道其他方法。 -
那你真的应该回到基础,因为你在这里做的事情将来会让你很头疼。如果只是对您需要的表格进行排序,这不是什么大问题,请不要继续在这里拼凑的内容
标签: javascript reactjs sorting