【发布时间】:2020-10-27 09:47:09
【问题描述】:
单击表格标题以对每列进行排序时,我在设置方向箭头时遇到了一个小问题。该表是动态创建的,如下面的代码所示。
我想要实现的是箭头只在点击每一列时出现,在切换列时消失。 我设法做的是切换箭头,但即使在页面加载时它也会出现在所有列上,这是我不想要的。
您有什么建议吗?我觉得没主意了……
这里是sn-p类:
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', key, 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);
【问题讨论】:
标签: reactjs lodash jsx css-tables