首页 > 解决方案 > 如何不使用空对象?

问题描述

我有这样的对象:

let collection = {
  first: '',
  second: '',
  third: '',
  Fourth: '',
};

我的问题是,我在平面列表中使用它并且一些属性是空的,所以我不想使用它们,因为当我把它们放在一个盒子里时,它们会占用空间。我该如何处理?

这是我的代码:

<View style={styles.container}>
  <ScrollView>
    <FlatList 
      data={this.state.AllMetarials}
      extraData={this.state}
      keyExtractor={(item, index) => index.toString()}
      numColumns={1}
      renderItem={ ({ item }) => {
        return ( 
          <View style={{ width: '50%', marginLeft: '2%', marginTop: '2%', alignItems: 'center', justifyContent: 'center', backgroundColor: '#00cec9', opacity: 0.7 }} >
            <Text>{item.first}</Text>
            <Text>{item.second}</Text> 
            <Text>{item.third}</Text>
            <Text>{item.Fourth}</Text>
          </View>
        );
      }}
    />
  </ScrollView>
</View>

编辑:

我确实喜欢这个并且它有效

 <View style={{ width: '50%', height: 80, marginLeft: '2%', marginTop: '2%', alignItems: 'center', justifyContent: 'center', backgroundColor: '#00cec9', opacity: 0.7 }} >
                                {item.first!== '' ? <Text> { item.first} </Text> : undefined}
                                {item.second!== '' ? <Text> { item.second} </Text> : undefined}
                                {item.third!== '' ? <Text> { item.third} </Text> : undefined}
                                {item.Fourth!== '' ? <Text> { item.Fourth} </Text> : undefined}
                            </View>

标签: react-native

解决方案


您的对象可能如下所示:

const myObject = {
  first: '',
  second: '',
}

然后您可以将其用作:

<View style={styles.container}>
  <ScrollView>
    <FlatList 
      data={this.state.AllMetarials}
      extraData={this.state}
      keyExtractor={(item, index) => index.toString()}
      numColumns={1}
      renderItem={ ({ item }) => {
        return ( 
          <View style={{ width: '50%', marginLeft: '2%', marginTop: '2%', alignItems: 'center', justifyContent: 'center', backgroundColor: '#00cec9', opacity: 0.7 }} >
            {item.first && <Text>{item.first}</Text>}
            {item.second && <Text>{item.second}</Text>} 
            {item.third && <Text>{item.third}</Text>}
            {item.Fourth && <Text>{item.Fourth}</Text>}
          </View>
        );
      }}
    />
  </ScrollView>
</View>

在 javascript&&中将确保仅当评估值不为 null、不为空、不为零或未定义时才执行下一条语句。


推荐阅读