jsx中的功能图反应本机

时间:2019-02-22 14:52:55

标签: javascript reactjs react-native jsx

在我的程序中以本机方式编写我有以下代码段:

getCompanyFunction() {
  const { enterprises, navigation } = this.props;
  return (
    <ScrollView horizontal>
      <View style={{ display: 'flex', flexDirection: 'row', flexWrap: 'nowrap' }}>
        { enterprises.map((enterprise) => {
          return (
            <Card key={enterprise.id} containerStyle={{ width: Dimensions.get('window').width - 50 }}>
              <ListItem
                title={enterprise.name}
                subtitle={(
                  <View>
                    <Text style={{ color: theme.text.default }}>
                      {enterprise.fonction}
                    </Text>
                    <Text style={{ color: theme.palette.text.default }}>
                      {enterprise.location || ''}
                    </Text>
                  </View>
                )}
                onPress={enterprise.id && (() => handleItemPress(enterprise.id, navigation))}
              />
            </Card>
          );
        })}
      </View>
    </ScrollView>
  );
}

在我的示例中,我有三个企业,但结果中只有第一个是明显的。但是map函数应该迭代我的数组吗?

谢谢!

1 个答案:

答案 0 :(得分:0)

map函数返回一个包含其操作结果的新数组。

MDN文档:

  

map()方法创建一个新数组,其结果是在调用数组中的每个元素上调用提供的函数。

您可以使用FlatList组件从map函数中渲染结果数组。

下面是一个有关如何实现的示例(假设您不需要更改enterprises数据):

renderCard = (enterprise) => {
    return (
        <Card key={enterprise.id} containerStyle={{ width: Dimensions.get('window').width - 50 }}>
            <ListItem
                title={enterprise.name}
                subtitle={(
                    <View>
                        <Text style={{ color: theme.text.default }}>
                            {enterprise.fonction}
                        </Text>
                        <Text style={{ color: theme.palette.text.default }}>
                            {enterprise.location || ''}
                        </Text>
                    </View>
                )}
                onPress={enterprise.id && (() => handleItemPress(enterprise.id, navigation))}
            />
        </Card>
    );
}

getCompanyFunction() 
  const { enterprises, navigation } = this.props;
  return (
    <ScrollView horizontal>
      <View style={{ display: 'flex', flexDirection: 'row', flexWrap: 'nowrap' }}>
        <FlatList
        data={enterprises}
        renderItem={({ item }) => renderCard(item)} />
      </View>
    </ScrollView>
  );
}

您不一定需要使用组件来呈现组件列表,但这通常是这样做的最佳方法。