问题描述
在单击表格标题以对每一列进行排序时,我在设置方向箭头时遇到了一个小问题。该表是动态创建的,如下面的代码所示。
我想要实现的是仅在单击每列时出现的箭头,而在切换列时消失。 我设法做到的是切换箭头,但它甚至在页面加载时也出现在所有列上,这是我不想要的。
您对此有何建议?我觉得没主意...
这是他的课程摘要:
import { connect } from 'react-redux';
import { orderBy } from "lodash";
class Test extends React.Component {
constructor(props) {
super(props);
this.state = {
currentlydisplayed: this.props.games,sortParams: {
direction: undefined
}
};
this.handleColumnHeaderClick = this.handleColumnHeaderClick.bind(this);
}
handleColumnHeaderClick(sortKey,e) {
const {
currentlydisplayed,sortParams: { direction }
} = this.state;
// Check,what direction Now should be
const sortDirection = direction === "desc" ? "asc" : "desc";
// performing the column switch and class toggle
this.setState(prevstate => ({ editingContactId: prevstate.editingContactId === sortKey? null:sortKey}))
// Sort collection
const sortedCollection = orderBy(currentlydisplayed,[sortKey],[sortDirection]);
//Update component state with new data
this.setState({
currentlydisplayed: sortedCollection,sortParams: {
direction: sortDirection
}
});
}
printObj(type='body',obj) {
const content = [];
for(const [key,value] of Object.entries(obj)) {
content.push(this.buildCell(type,key,value));
}
return content;
}
buildCell(type='body',value) {
return (
<>
{ type==='header' ? <th className={key === this.state.editingContactId ? 'sort-desc' : 'sort-asc'} onClick={(e) => this.handleColumnHeaderClick(key,e)} key={key}>{key}</th> : <td key={key}>{value}</td> }
</>
);
}
render() {
return (
<>
<table>
<thead>
<tr>
{this.state.currentlydisplayed.length !== 0 &&
this.printObj('header',this.props.games[0])
}
</tr>
</thead>
<tbody>
{this.state.currentlydisplayed.length !== 0 &&
this.state.currentlydisplayed.map((obj,key) => {
return (
<tr key={key}>
{ this.printObj('body',obj) }
</tr>
);
})
}
</tbody>
</table>
</>
);
}
}
export default connect(
mapStatetoProps
)(Test);
解决方法
使用排序方向尝试类似的操作。
<th className={key === this.state.editingContactId
? this.sortParams.direction === "asc"
? "sort-asc"
: "sort-desc"
: ""}