首页 > 解决方案 > 如何在本机反应中根据其键操作映射项

问题描述

.map用来在屏幕上显示我的数组项。数组 ->[Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday]

下面是我的代码:

<ScrollView
  horizontal={true}
  showsHorizontalScrollIndicator={false}
  contentContainerStyle={styles.horizontalView}>
  {weekArray.map((item, key) => ((
        <Text key={key} style={styles.TextStyle} onPress={_press}>
          {" "}{item.day}{" | "}
        </Text>
      ))
  )}
</ScrollView>;

我的输出方式如下:

Monday | Tuesday | Wednesday| Thursday| Friday | Saturday | Sunday |

我想删除|星期天之后的最后一个。我对学习地图很陌生,所以我不知道该怎么做。我知道它对键做了一些事情,但我不知道该怎么做。

标签: react-native

解决方案


第二个参数mapindex... 所以你可以lastItem用这种方式检查 ...

{weekArray.map((item, key) => (
        <Text key={key} style={styles.TextStyle} onPress={_press}>
          {key === weekArray.length - 1 ? ` ${item.day}` : ` ${item.day} | `}
        </Text>
      ))}

使用if-cond...

  const renderItem = (index, item) => {
    if (index === weekArray.length - 1) {
      return ` ${item.day}`;
    }
    return ` ${item.day} | `;
  };
  

...

  {weekArray.map((item, key) => (
    <Text key={key} style={styles.TextStyle} onPress={_press}>
      {renderItem(key, item)}
    </Text>
  ))}

推荐阅读