gpt4 book ai didi

javascript - 在 React.js 中映射数组时仅设置少数元素的样式

转载 作者:行者123 更新时间:2023-11-28 17:31:50 25 4
gpt4 key购买 nike

如果你能帮我解决这个问题,那将会非常有帮助,因为我花了很多时间在这上面。

我有很多小时,我正在映射它并返回列表项。问题是我只想突出显示/着色其他数组(hours2)中的那些项目。

这是我的代码块:

const hours = ["09:00", "10:00", "11:00", "12:00", "13:00", "14:00"];

const hours2 = ["11:00", "12:00"];

const renderedHours = hours.map(item => (
<li
style={{
backgroundColor: item === hours2.map(item => item) ? "yellow" : "pink"
}}
// above I would like to select only those items which are equal to items from second array, but that does not work.

key={item}
className="hoursListItem"
onClick={e => {
this.handleClick(e);
}}
>
{item}
</li>
));

提前谢谢您!

最佳答案

您可以使用Javascript some method检查数组中是否存在元素:

const hours = ["09:00", "10:00", "11:00", "12:00", "13:00", "14:00"];

const hours2 = ["11:00", "12:00"];

const renderedHours = hours.map(item => {
const styles = {
backgroundColor: hours2.some(h => h === item) ? "yellow" : "pink"
}

return (
<li
style={styles}
key={item}
className="hoursListItem"
onClick={e => {
this.handleClick(e);
}}
>
{item}
</li>
);
});

关于javascript - 在 React.js 中映射数组时仅设置少数元素的样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50188151/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com