reactjs - 有没有办法将 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 不能像这样在一起。这个问题的可能解决方案是什么?
解决方案
这不起作用的原因是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>
))}
推荐阅读
- python - Python 例外:数据必须是一维的
- python - 用于 python 的开源 Whatsapp 业务 API 客户端
- reactjs - 关闭对话框时更改页面地址(材质 ui,react-router)
- facebook - Facebook 帖子中的 URL 添加了额外的“www”。
- swift - 向观察者添加完成时应用程序崩溃
- javascript - 当 TextField 在 Material UI 中聚焦时显示帮助文本
- html - “'”赛普拉斯中的单引号符号
- python - 如何使用 Python 的多处理模块多次运行一个函数?
- java - SimpleDateFormat 解析 JDK 11 和 12 与 JDK 14
- c - 创建后立即对哈希表条目进行读取访问冲突