如何解决反应-将方向箭头设置为表格标题
在单击表格标题以对每一列进行排序时,我在设置方向箭头时遇到了一个小问题。该表是动态创建的,如下面的代码所示。
我想要实现的是仅在单击每列时出现的箭头,而在切换列时消失。 我设法做到的是切换箭头,但它甚至在页面加载时也出现在所有列上,这是我不想要的。
您对此有何建议?我觉得没主意...
这是他的课程摘要:
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"
: ""}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。