简体   繁体   English

如何在 React Native 的列表中为特定位置的项目设置不同的样式?

[英]How to have different style for items at certain locations in a list in React Native?

I'm trying to have different styles for the first and last items in a list, like the picture below:我正在尝试为列表中的第一项和最后一项使用不同的 styles,如下图所示:

在此处输入图像描述

Where the first card has rounded corner on the upper right and the last card has rounded corner on the lower right.第一张牌在右上角有圆角,最后一张牌在右下角有圆角。 I'm still figuring out how to approach this.我仍在想办法解决这个问题。

Is there any way to pass the location of an item in the list to the item itself so it can be applied to a different style?有没有办法将列表中项目的位置传递给项目本身,以便它可以应用于不同的样式? Or there are other better approaches?还是有其他更好的方法?

Also, I would like to have the card to have both rounded upper and lower right corners if there's only one card present, like below:另外,如果只有一张卡片,我希望卡片的右上角和右下角都圆润,如下所示:

在此处输入图像描述

When rendereing items with ListView/FlatList/SectionList rendering method has index parameter.当使用 ListView/FlatList/SectionList 渲染方法渲染项目时,有 index 参数。 You can use that index to figure out if the item is first or last and give conditional styling for that item.您可以使用该索引来确定该项目是第一个还是最后一个,并为该项目提供条件样式。

Example示例

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} />
}

With styled-components , you can do this:使用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 }
        />
      })}
      ...
    </>
  );
}

Much more readable imho.更易读恕我直言。

Adding to @bennygenel 's answer we can use terniary operator as well添加到@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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM