【问题标题】:How can I render only first object from array? React Native Flatlist如何仅渲染数组中的第一个对象? React Native 扁平列表
【发布时间】:2020-10-16 18:59:12
【问题描述】:

如何仅渲染 Array 中的第一个对象?我知道我需要放 [0] 但我不知道具体在哪里?我尝试了 item[0] 和 item.answers[0]。还有其他方法吗?我不知道还能写什么,所以系统允许我发布我的问题。哈哈

const DATA = [
  {
    id: "2222",
    question:
      "In class, how often do you purposely encourage others around you?",
    answers: [
      {
        answerText:
          "Bully: Use physical aggression to get my own way. Pick on others a lot",
      }
    ],
  },
  {
    id: "3333",
    question:
      "In class, how often do you purposely encourage others around you?",
    answers: [
    
      {
        answerText:
          "Manipulating: Try to get others to do what you want by telling",
      },
    ],
  },
];

const Item = ({ item, onPress, style }) => {
  return item.answers
    .map((x) => x.answerText)
    .map((value, i) => (
      <TouchableOpacity
        onPress={onPress}
        style={[styles.item, style]}
        keyExtractor={i}
      >
        <Text style={styles.title}>{value}</Text>
      </TouchableOpacity>
    ));
};

const renderItem = ({ item }) => {
    // const backgroundColor = item.id === selectedId ? "#6e3b6e" : "#f9c2ff";
    return (
      <Item
        item={item}
        onPress={() => {
          console.log(item);
        }}
        style={{ backgroundColor: Colors.primary }}
      />
    );
  };

  return (
    <SafeAreaView style={styles.container}>
      <FlatList
        data={DATA}
        renderItem={renderItem}
        keyExtractor={(item) => item.id}
      />
    </SafeAreaView>
  );
};

【问题讨论】:

    标签: react-native react-native-flatlist


    【解决方案1】:

    渲染项目函数还提供索引参数,你可以检查,如果 index!=0 比返回 null

    【讨论】:

      【解决方案2】:

      这可能会有所帮助

      const Item = ({ item, onPress, style }) => {
        return <TouchableOpacity
                onPress={onPress}
                style={[styles.item, style]}
               >
               <Text style={styles.title}>{item.answers[0].answerText}</Text>
            </TouchableOpacity>
      };
      

      【讨论】:

      • 我认为应该可以。我已经更新了,请检查
      • 不,它不起作用,问题的真正解决方案是不同的,我已经发现了
      猜你喜欢
      • 1970-01-01
      • 2019-06-01
      • 2020-11-20
      • 2023-04-04
      • 1970-01-01
      • 1970-01-01
      • 2021-07-07
      • 2020-03-03
      • 2021-04-17
      相关资源
      最近更新 更多