在 React.js 中映射数组时仅设置几个元素的样式



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

我有一系列小时,我正在映射它并返回列表项。问题是我只想突出显示/着色其他数组(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>
));

提前谢谢你!

您可以使用 Javascriptsome方法来检查数组中是否存在元素:

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>
);
});

只需使用indexOf在第二个数组中搜索值,如果找不到元素,则返回索引或-1

const renderedHours = hours.map(item =>
<li 
style={{'backgroundColor': hours2.indexOf(item) > -1 ? 'yellow' : 'pink'}}
key={item} 
className="hoursListItem"
onClick={(e) => {this.handleClick(e)}}
>
{item}
</li>)

在这里,hours2中的项目将具有黄色背景,其他项目将具有粉红色背景。

您可以使用includes()方法来检查当前item是否在array2内。

style={{'backgroundColor': hours2.includes(item) ? 'yellow' : 'pink'}}

如果您只想background-colorarray2中找到的项目,则可以使用它。

style={{'backgroundColor': hours2.includes(item) && 'yellow'}}

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': hours2.includes(item) ? 'yellow' : 'pink'}}
key={item} 
className="hoursListItem"
onClick={(e) => {this.handleClick(e)}}>{item}
</li>)
ReactDOM.render(
<RenderedHours  />,
document.getElementById('root')
);
<script src="https://unpkg.com/react@16.3.2/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@16.3.2/umd/react-dom.development.js"></script>
<div id="root"></div>

我会使用类来做到这一点,而不是像那样使用内部样式:

className={`hoursListItem ${hours2.includes(item) ? 'true' : 'false' }`}

相关内容

最新更新