![](/img/trans.png)
[英]How to conditionally overwrite a style with a different style in React Native?
[英]How to have different style for items at certain locations in a list in React Native?
当使用 ListView/FlatList/SectionList 渲染方法渲染项目时,有 index 参数。 您可以使用该索引来确定该项目是第一个还是最后一个,并为该项目提供条件样式。
示例
renderItem = ({item, index}) => {
if (index === 0) return <ListItem style={styles.firstItem} data={item} />
else if (index === (this.state.data.length -1)) return <ListItem style={styles.lastItem} data={item} />
else return <ListItem style={styles.item} data={item} />
}
render() {
return <FlatList data={this.state.data} renderItem={this.renderItem} />
}
使用styled-components ,您可以这样做:
import styled, { css } from "styled-components";
const Item = styled.div`
background-color: red;
${props => props.isFirst && css`
background-color: blue;
`}
${props => props.isLast && css`
background-color: yellow;
`}
`;
function() {
const items = [];
return (
<>
...
{items.map((item, index) => {
<Item
key={item.id}
isFirst={index === 0}
isLast={index === items.length - 1 }
/>
})}
...
</>
);
}
更易读恕我直言。
添加到@bennygenel 的答案,我们也可以使用三元运算符
renderItem = ({item, index}) => {
return <ListItem style={index === 0 ? styles.firstItem : index === (this.state.data.length -1) ? styles.lastItem : styles.item } data={item} />
}
render() {
return <FlatList data={this.state.data} renderItem={this.renderItem} />
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.