抱歉,这是新手问题,通常在组件中使用<List>{this.state.variable.map...}</List>
。但是如何在三元运算符中使用 .map 函数/条件渲染中的任何函数?在下面使用此语法时给出了错误的语法
法典:
{group.category !== "place" ?
<ListItem
title={"Foods"}
leftIcon={{
name: "food",
type: "material-community",
color: this.state.themeStore.primaryDarkColor
}}
subtitle={group.category}
subtitleStyle={{
color: this.state.themeStore.primaryDarkColor
}}
titleStyle={{ color: this.state.themeStore.primaryDarkColor }}
onPressRightIcon={() => {
this.showFoodsItem();
}}
rightIcon={{
name: "md-arrow-dropdown-circle",
type: "ionicon",
color: this.state.themeStore.primaryLightColor
}}
/>
this.state.foods.map((item, i) => (
<ListItem
key={i}
title={item.name}
titleStyle={{
color: this.state.themeStore.primaryDarkColor
}}
avatar={{ uri: item.imageSource }}
rightIcon={{
name: "md-add-circle",
type: "ionicon",
color: this.state.themeStore.primaryLightColor
}}
onPressRightIcon={() => this.addExistingPlace(item)}
/>
)
: (
<View />
)}
这不是三元运算符的问题。React 预计你会返回一个子级(或者在 React 16+ 的情况下 - 子级数组),但你有多个子级。
您可以通过重构代码来解决此问题:它将<ListItem>
数组准备为单独的代码块(但在render()
方法的语句之外return
然后将此数组直接放入返回的 JSX 树中(在 React 16+ 的情况下)或使用额外的包装器,如React.createElement('div',{},...listItems)
因此,您的代码可能如下所示:
render() {
let items = [
<ListItem
title={"Foods"}
leftIcon={{
name: "food",
type: "material-community",
color: this.state.themeStore.primaryDarkColor
}}
subtitle={group.category}
subtitleStyle={{
color: this.state.themeStore.primaryDarkColor
}}
titleStyle={{color: this.state.themeStore.primaryDarkColor}}
onPressRightIcon={() => {
this.showFoodsItem();
}}
rightIcon={{
name: "md-arrow-dropdown-circle",
type: "ionicon",
color: this.state.themeStore.primaryLightColor
}}
/>
];
this.state.foods.forEach((item, i) => (
items.push(<ListItem
key={i}
title={item.name}
titleStyle={{
color: this.state.themeStore.primaryDarkColor
}}
avatar={{uri: item.imageSource}}
rightIcon={{
name: "md-add-circle",
type: "ionicon",
color: this.state.themeStore.primaryLightColor
}}
onPressRightIcon={() => this.addExistingPlace(item)}
/>
)
));
return group.category !== "place" ? React.createElement('div', {}, ...items) : <View/>;
}