【问题标题】:Render multiple JSX elements from object array从对象数组中渲染多个 JSX 元素
【发布时间】:2018-06-13 12:28:51
【问题描述】:

我在生成多个 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>
));

【问题讨论】:

    标签: javascript arrays object react-native


    【解决方案1】:

    不是这个

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

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

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

    【讨论】:

      【解决方案2】:

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

      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>
      
               )
      }
      

      【讨论】:

        猜你喜欢
        • 2021-02-01
        • 1970-01-01
        • 2021-11-09
        • 2022-11-01
        • 2018-12-29
        • 2018-03-07
        • 2021-12-07
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多