如何显示作为道具传递给功能组件的数组元素?

时间:2018-10-06 11:52:49

标签: javascript reactjs react-native

我创建了amenitiesArray,其中包含club_house,swimming_pool等元素。我正在使用amenitiesArray.map()上映射,但是当我将其作为道具传递时,我无法在屏幕上显示为什么?

console.log(amenitiesArray)是:

0:"Gymnasium"
1:"swimming_pool"
2:"club_house"
3:"childrens_play_area"
4:"multipurpose_room"
5:"security"
6:"jogging_track"
7:"power_backup"
8:"landscaped_gardens"
9:"car_parking"

代码:

const DisplayAmenities = ({ name }) => (
  <Text style={{ color: 'black', fontSize: 16 }}>{name}</Text>
);

export default class Project extends Component {
  render() {
    let amenitiesArray = [];

    for (var key in amenities[0]) {
      if (amenities[0][key] === 'Yes') {
        amenitiesArray.push(key);
      }
    }
    console.log(amenitiesArray);

    return (
      <ScrollView>
        <View style={{ marginTop: 20 }}>
          {amenitiesArray.map(val => {
            <DisplayAmenities name={val} />;
          })}
        </View>
      </ScrollView>
    );
  }
}

以上代码在屏幕上未显示任何内容?为什么这样?

2 个答案:

答案 0 :(得分:2)

因为您忘记退回该组件。尝试像这样修复:

 return (
      <ScrollView>
        <View style={{ marginTop: 20 }}>
          {amenitiesArray.map((val,index) => {
            return <DisplayAmenities key={index} name={val} />;  //fixed
          })}
        </View>
      </ScrollView>
    );

简而言之,您可以这样省略大括号

 return (
      <ScrollView>
        <View style={{ marginTop: 20 }}>
          {amenitiesArray.map((val,index) => <DisplayAmenities key={index} name={val} /> )}
        </View>
      </ScrollView>
    );

答案 1 :(得分:1)

  {amenitiesArray.map(val => {
    <DisplayAmenities name={val} />;
  })}

缺少显式返回,map回调函数将数组映射到undefined的数组。

对于隐式箭头返回,应为:

  {amenitiesArray.map(val => 
    <DisplayAmenities name={val} />;
  )}

使用array-callback-return ESLint rule可以避免这种错误。