首页 > 解决方案 > 有没有办法将 JSX 元素和附加代码结合起来?

问题描述

{this.state.categories && this.state.dishes && this.state.categories.map((item) => (
  <Text style={{fontSize: 30, fontWeight: 'bold', padding: 5, backgroundColor: '#f0f0f0', borderWidth: 0.175}}>{item['dish_categories_name']}</Text>
  this.filterDishesOnCategory(this.filterList(this.state.dishes), item['dish_categories_id']).map((listItem) => (
    <View key={listItem['dish_name']} >
      <Dish name={listItem['dish_name']} info={listItem['dish_description']} cost={listItem['dish_price']}/>
    </View>
  ))
))}

我正在尝试映射类别数据,然后生成一个带有类别名称的文本元素。之后,该类别中的菜肴被映射并显示附加的菜肴信息。但是,很明显 Text 标签和 this.filterDishesOnCategory 不能像这样在一起。这个问题的可能解决方案是什么?

标签: reactjsreact-native

解决方案


这不起作用的原因是map它只能返回一个父组件。有一种东西叫做Fragment专门为这种场景制作的。Fragment 组件不呈现任何 HTML,它适用于这种情况,您需要一个父元素来满足 React 的唯一目的。

您可以从 react 包中导入Fragment组件。

import React, { Fragment } from 'react';

this.filterDishesOnCategory所以现在我们只需添加一个 Fragment 作为父组件,并在您的方法中添加花括号。

{this.state.categories && this.state.dishes && this.state.categories.map((item) => (
    <Fragment>
        <Text style={{fontSize: 30, fontWeight: 'bold', padding: 5, backgroundColor: '#f0f0f0', borderWidth: 0.175}}>{item['dish_categories_name']}</Text>
        {this.filterDishesOnCategory(this.filterList(this.state.dishes), item['dish_categories_id']).map((listItem) => (
            <View key={listItem['dish_name']} >
                <Dish name={listItem['dish_name']} info={listItem['dish_description']} cost={listItem['dish_price']}/>
            </View>
        ))}
    </Fragment>
))}

推荐阅读