如何在React中制作递增箭头和递减箭头进行排序



我已经制作了一个表,现在我可以对多个列进行排序。我想要的是,在单击特定按钮后,我会在按钮上得到一个递增符号,如果再次单击,按钮上会得到一个递减符号。下面是我的函数代码,它可以更改列和方向,并以为例给出按钮

function change(set){
let direction='asc';
if(sortOrder==='asc'){
direction='desc';
}
setSortBy(set);
setSortOrder(direction);
}
<table>
<th><button onClick={()=>change('name')}>
Name
</button></th>
<th><button onClick={()=>change('total')}>
Total
</button></th>
</table>

所以任何人都可以告诉我如何实现箭头

对于简单的表内容排序,请尝试数据表。例如:https://www.npmjs.com/package/react-data-table-component

您应该维护状态中的列排序顺序。单击列/按钮时,将更新状态,更改将反映在渲染中。使用数据属性来标识列/按钮。而且,除非您在项目中使用单独的CSS库,否则只需使用unicode向上/向下箭头即可。

const {useState} = React;
function Example() {
// Use an object to maintain the column sort order
const [order, setOrder] = useState({ name: 'asc', total: 'asc' });
function handleClick({ target }) {

// Instead of attaching a handler to each button,
// there is one on the table, and we simply need to check
// that the element we've clicked on is a button instead.
if (target.nodeName === 'BUTTON') {
// Grab the type (name, total etc) from the data attribute
const { dataset: { type } } = target;
// Set the state of the new order
setOrder(prev => {
const newOrder = prev[type] === 'asc' ? 'desc' : 'asc';
return { ...prev, [type]: newOrder };
});
}
}
// Return the arrows
function getArrow(order) {
if (order === 'asc') return '↑';
return '↓';
}
return (
<table onClick={handleClick}>
<th><button data-type="name">Name {getArrow(order.name)}</button></th>
<th><button data-type="total">Total {getArrow(order.total)}</button></th>
</table>
);
};
// Render it
ReactDOM.render(
<Example />,
document.getElementById("react")
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.1/umd/react-dom.production.min.js"></script>
<div id="react"></div>

最新更新