【发布时间】:2021-05-31 16:36:41
【问题描述】:
我在按下按钮时生成卡片。这些卡片有一个随机生成的数字,介于 0 到 100 之间。我正在尝试设置一个组件或函数,当我单击排序按钮时,它允许我按数字顺序升序或降序或同时对所有这些卡片进行排序。我已经尝试了以下代码。请记住,这都包含在同一个 App 组件中。
随机数在加卡组件中生成。
我觉得我非常接近,但我无法弄清楚我错过了什么。
const sortTypes = {
up: {
class: "sort-up",
fn: (a, b) => a.number - b.number,
},
down: {
class: "sort-down",
fn: (a, b) => b.number - a.number,
},
default: {
class: "sort",
fn: (a, b) => a,
},
};
const sortAll = () => {
state = {
currentSort: 'default'
};
onSortChange = () => {
const { currentSort } = this.state;
let nextSort;
if (currentSort === 'down') nextSort = 'up';
else if (currentSort === 'up') nextSort = 'default';
else if (currentSort === 'default') nextSort = 'down';
this.setState({
currentSort: nextSort
});
};
};
return (
<body>
<header>
<div className="ui buttons">
<button type="button" onClick={addCard} className="ui button mb-1 mt-1 mr-1"><i className="plus icon"></i>Add Card</button>
<div className="or mb-1 mt-1"></div>
<button type="button" onClick={sortAll} className="ui positive button mb-1 mt-1 mr-1"><i className="redo icon"></i>Sort All</button>
</div>
</header>
【问题讨论】:
-
如果你能沙箱这个会很棒。
-
sortAll有点像一个反应组件,它的名字不像一个,但它有状态......但你作为回调附加?onSortChange在哪里调用以“选择”您要使用的排序功能?您在哪里应用任何排序功能? -
有一个指向代码框的链接。 onSortChange 在第 72 行。排序功能应该在第 94 行应用。
-
我觉得我开始做的很正确,但我从来没有在 React 中做过这样的事情,所以我不确定一切都需要去哪里。
标签: javascript reactjs sorting random-seed card