从对象数组渲染多个JSX元素

时间:2018-06-13 12:28:52

标签: javascript arrays object react-native

我无法生成多个JSX元素,例如(来自对象数组的数据中的多个文本字段或按钮)它会在一个JSX标记/元素中生成所有数组内容。我怎么能让它生成多个标签?提前谢谢。

const labourers = [
  {
    id: 1,
    name: 'Velry Mokwena',
    skills: ['Domestic Cleaning'],
    location: ['Pretoria'],
    rating: 100,
  },
  {
    id: 2,
    name: 'Isaac Cindi',
    skills: ['Gardening', 'Painting', 'Plastering', 'General Labour'],
    location: ['Centurion'],
    rating: 100,
  },
  {
    id: 3,
    name: 'Joseph Mahlangu',
    skills: ['Bricklaying', 'Plastering'],
    location: ['Menlo Park', 'Pretoria'],
    rating: 100,
  },
];

var labourer = labourers.map(labourer => (
  <View key={labourer.id} style={{display: 'flex', marginBottom: 20, backgroundColor: 'gray', padding: 20}}>
    <Text style={{textAlign: 'center'}}>{labourer.name}</Text>
    <Text style={{textAlign: 'center'}}>{labourer.skills}</Text>
    <TouchableOpacity><Text style={{textAlign: 'center'}}>{labourer.location}</Text></TouchableOpacity>
  </View>
));

2 个答案:

答案 0 :(得分:1)

而不是这个

 <Text style={{textAlign: 'center'}}>{labourer.skills}</Text>

将数组连接到单个文本字符串,只需将其映射到另一个jsx元素:

{labourer.skills.map(skill => 
 <Text style={{textAlign: 'center'}}>{skill}</Text>
)}

答案 1 :(得分:0)

您需要对迭代逻辑进行一些修改,如下所示

render(){
.
.
.
          var labourer = labourers.map(function(labourer){
                  return(  <View key={labourer.id} style={{display: 'flex',marginBottom: 20, backgroundColor: 'gray', padding: 20}}>
                             <Text style={{textAlign: 'center'}}>{labourer.name}</Text>
                             <Text style={{textAlign: 'center'}}>{labourer.skills}</Text>
                             <TouchableOpacity><Text style={{textAlign: 'center'}}>{labourer.location}</Text></TouchableOpacity>
                            </View> )
         });

         return (
                //render here
                <div>
                  labourer
                </div>

         )
}