在一个函数中使用 React useState 选择列表类型



我正在使用 React useState 来显示所选文章类型的文章列表。我已经设法使用两个单独的函数使其工作,但我想知道是否有办法在用户有许多不同的选项可供选择的情况下将其放入一个函数中?

function MostReadArticlesList() {
const [list, setList] = useState(mostReadArticles);
const [mostReadStyle, setMostReadStyle] = useState(styles["mostReadArticlesHeaderChosen"])
const [editorsChoiceStyle, setEditorsChoiceStyle] = useState(styles["editorsChoiceHeader"])
const [rankColor, setRankColor] = useState(styles.mostReadArticlesRankRed)
function selectMostRead() {
setList(mostReadArticles);
setMostReadStyle(styles["mostReadArticlesHeaderChosen"]);
setEditorsChoiceStyle(styles["editorsChoiceHeader"]);
setRankColor(styles.mostReadArticlesRankRed);
};
function selectEditorsChoice() {
setList(editorsChoiceArticles);
setMostReadStyle(styles["mostReadArticlesHeader"]);
setEditorsChoiceStyle(styles["editorsChoiceHeaderChosen"]);
setRankColor(styles.mostReadArticlesRankBlue);
};
return (
<div className={styles.mostReadArticlesListContainer}>
<div className={styles.mostReadArticlesHeaderDiv}>
<Button className={mostReadStyle} onClick={selectMostRead}>
<Icon icon="assets/img/circle-growth-icon.png" />
<span>Most Read</span>
</Button>
<Button className={editorsChoiceStyle} onClick={selectEditorsChoice}>
<Icon icon="assets/img/notes-star-icon.png" />
<span>Editors Choice</span>
</Button>
</div>
<div className={styles.mostReadArticlesList}>
{list.map((article) => (
<MostReadArticlesCard
id={article.id}
rank={article.rank}
headline={article.headline}
date={article.date}
rankColor={rankColor}
/>
))}
</div>
</div>
);
}
export default MostReadArticlesList;

我不确定那里在做什么,您是否使用 CSS 样式对文章进行排序?这很糟糕。你应该用JS对它们进行排序。

Array.sort()的例子:

const [list, setList] = useState(articles);
const sortBy = ( property ) = {
const newList = [...list]; // This is not fully immutable - but should work
newList.sort( (a, b) => {
if(a[property] < b[property]) { return -1; }
if(a[property] > b[property]) { return 1; }
return 0;
})
setList( newList );
}
...
<button onClick={() => sortBy('rank')}>By rank</button>
<button onClick={() => sortBy('headline')}>By headline</button>

/编辑

一个函数来管理两个列表(理论上你可以使用一个状态(,我建议你对所有活动按钮使用一个类active而不是"mostReadArticlesHeaderChosen"。

const [list, setList] = useState(mostReadArticles);
const [active, setActive] = useState('mostRead');
function selectList( listName ) {
switch(listName) {
case 'mostRead': {
setList(mostReadArticles);
setActive('mostRead');
}
case 'editorsChoice': {
setList(editorsChoiceArticles);
setActive('editorsChoice');
}
default:
}
}
...
<button 
class={ active === 'mostRead' ? 'mostReadArticlesHeaderChosen' : 'mostReadArticlesHeader'}
onClick={() => selectList('mostRead')}
>
Most Read
</button>
<button 
class={ active === 'editorsChoice' ? 'editorsChoiceHeaderChosen' : 'editorsChoiceHeader'} 
onClick={() => selectList('editorsChoice')}
>
Editor's Choice
</button>

相关内容

  • 没有找到相关文章

最新更新