react循环时如何控制样式
循环渲染与样式控制
在React中通过循环渲染元素时,可以通过以下方式动态控制样式:
内联样式动态绑定
const items = ['Item1', 'Item2', 'Item3'];
const colors = ['#ff0000', '#00ff00', '#0000ff'];
function List() {
return (
<ul>
{items.map((item, index) => (
<li
key={index}
style={{
color: colors[index],
fontWeight: index % 2 === 0 ? 'bold' : 'normal'
}}
>
{item}
</li>
))}
</ul>
);
}
动态CSS类名
import './styles.css';
function List() {
return (
<ul>
{items.map((item, index) => (
<li
key={index}
className={`item ${index === activeIndex ? 'active' : ''}`}
>
{item}
</li>
))}
</ul>
);
}
CSS Modules方案
import styles from './List.module.css';
function List() {
return (
<ul className={styles.list}>
{items.map((item, index) => (
<li
key={index}
className={`${styles.item} ${index === 0 ? styles.firstItem : ''}`}
>
{item}
</li>
))}
</ul>
);
}
styled-components动态样式
import styled from 'styled-components';
const StyledItem = styled.li`
color: ${props => props.active ? 'red' : 'black'};
background: ${props => props.index % 2 === 0 ? '#eee' : '#fff'};
`;
function List() {
return (
<ul>
{items.map((item, index) => (
<StyledItem
key={index}
active={index === activeIndex}
index={index}
>
{item}
</StyledItem>
))}
</ul>
);
}
条件样式处理
可以根据数据状态或索引值应用不同样式:
function List({ items }) {
return (
<ul>
{items.map((item, index) => {
const isSpecial = item.priority === 'high';
const itemClass = isSpecial ? 'special-item' : 'normal-item';
return (
<li
key={item.id}
className={itemClass}
style={{
textDecoration: item.completed ? 'line-through' : 'none'
}}
>
{item.text}
</li>
);
})}
</ul>
);
}
性能优化建议
对于大型列表,应避免在渲染时进行复杂的样式计算。可以将样式预处理为静态对象或使用CSS类名切换:
const styleMap = {
high: { color: 'red', fontWeight: 'bold' },
normal: { color: 'black' }
};
function List({ items }) {
return (
<ul>
{items.map(item => (
<li key={item.id} style={styleMap[item.priority]}>
{item.text}
</li>
))}
</ul>
);
}





