3
我目前的執行情況:使用React實現可排序表的正確方法是什麼?
export const SORT_ORDER = {
ASC: "ascending",
DESC: "descending",
OTHER: "other"
};
export default class Table extends React.Component {
constructor(props) {
super(props);
this.sortIcon = new Map();
this.sortIcon.set(SORT_ORDER.ASC, sortAsc);
this.sortIcon.set(SORT_ORDER.DESC, sortDesc);
this.sortIcon.set(SORT_ORDER.OTHER, sortOther);
this.state = {
sortField: this.props.defaultSortColumn,
sortOrder: this.props.defaultSortOrder
};
}
componentDidMount() {
this.sort(this.props.defaultSortColumn, this.props.defaultSortOrder)();
}
retrieveOrder = (columnId) => {
return columnId === this.state.sortField ? this.state.sortOrder : SORT_ORDER.OTHER;
};
nextOrder = (current) => {
if (current === SORT_ORDER.DESC) {
return SORT_ORDER.ASC;
} else if (current === SORT_ORDER.ASC) {
return SORT_ORDER.DESC;
} else {
return this.props.defaultSortOrder;
}
};
sort = (columnId, order) =>() => {
let descriptor = this.props.structure[columnId];
let values = this.props.value.slice();
let orderFactor = order === SORT_ORDER.ASC ? 1 : -1;
values.sort((a, b) => {
let first = descriptor.render(a);
let second = descriptor.render(b);
return first > second ? orderFactor : first < second ? -orderFactor : 0;
});
this.setState({
sortField: columnId,
sortOrder: order
});
this.props.onSort(values);
};
renderHeader = (id, descriptor) => {
let order = this.retrieveOrder(id);
let iconSrc = this.sortIcon.get(order);
let nextOrder = this.nextOrder(this.retrieveOrder(id));
return (
<th key={id} className={descriptor.headStyle}>
<a href="#" aria-sort={order} onClick={this.sort(id, nextOrder)}>
<img src={iconSrc}/>
{descriptor.label}
</a>
</th>
);
};
render() {
return (
<table>
Table structure
</table>
);
}
}
父組件聲明它在接下來的方式:
<Table structure={this.tableHeader} value={this.state.tableValue} onSort={this.handleChange('tableValue')}
defaultSortColumn="created" defaultSortOrder={SORT_ORDER.DESC} />
表值在道具定義爲value
。 onSort
是一個函數,用於更改父組件的狀態=>它更改表值。另外,我還有defaultSortColumn
和defaultSortOrder
可以在填充表格後排序表格。
問題是我的表可以在頁面多次聲明。
所以,
1)我無法將表格值存儲在其狀態。我是不是該?
2)如何在不使用componentDidMount
的情況下實現默認排序?使用當前的實現默認排序只發生一次,當調用componentDidMount
時,但頁面上有多個1 <Table/>
組件。 我試過使用componentWillReceiveProps
函數,但是當我改變sort
函數中的<Table/>
狀態時,它也被調用。所以我不能使用它。
我會建議使用生產 –
@MartinZinovsky現有的解決方案現有的解決方案不符合要求,因爲有錯誤的HTML佈局,例如div塊而不是html表等。 –
你檢查了哪些組件?我的意思是它們中有很多https://react.parts/web?search=table –