[英]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.