我有一个像这样的复杂对象:
{
"hot foods": [
{
"name": "something",
"ingredients": "something",
"price": 13
},
{
"name": "something",
"ingredients": "something",
"price": 13
}
],
"cold drinks": [
{
"name": "something",
"ingredients": "something",
"price": 13
},
{
"name": "something",
"ingredients": "something",
"price": 13
}
]
}
我想在可折叠组件中渲染它,该组件来自这里:https://www.npmjs.com/package/accordion-collapse-react-native
我希望它在 CollapseHeader 组件中渲染“热食”、“冷饮”,在 CollapseBody 组件中我想一一渲染这些对象数组。
但我无法弄清楚,因为我不太擅长 javascript,而且它不是我的核心语言。我只需要在 React Native 应用程序中以这种方式呈现它。
任何帮助或想法都会得到重视,我在互联网上找不到任何完全相同的示例。
这里让我向您展示我正在尝试的功能:
{
Object.keys(this.state.menuArr).map((category,index)=>{
return (
<Collapse>
<CollapseHeader>
<View>
<TouchableOpacity onPress={()=>{}} style={styles.waitressbutton}>
<Text> {category} {console.log(category)}</Text>
</TouchableOpacity>
</View>
</CollapseHeader>
{
this.state.menuArr[category].map((item,index)=>{
return(
<CollapseBody>
<Text>Ta daa!</Text>
<TouchableOpacity key={index} style={styles.addbutton} onPress={
}>
<Text key={Math.floor(Math.random() * 10000) + 1}> <Icon name='plus' color='#d7263d'/> {item} </Text>
</TouchableOpacity>
</CollapseBody>
);
}
)
}
</Collapse>
)
}
)
}
我的对象与我上面写的完全相同。这个函数只渲染类别名称,而不渲染 CollapseBody 部分的内部。
最佳答案
更好的方法是将数据作为数组传递并使用对象来分配属性。这样,您还可以直接从 react-native
使用 FlatList
或 SectionList
。但是当您指定要使用的库时,下面是示例代码:
import React, { Component } from 'react';
import{ View, Text, StyleSheet } from 'react-native';
import { AccordionList } from "accordion-collapse-react-native";
export default class App extends React.Component {
state = {
data : [
{
title: 'hot food',
data: [
{
"name": "something food",
"ingredients": "something",
"price": 13
},
{
"name": "something food 2",
"ingredients": "something",
"price": 13
}
]
},
{
title: 'hot food',
data: [
{
"name": "something food",
"ingredients": "something",
"price": 13
},
{
"name": "something food 2",
"ingredients": "something",
"price": 13
}
]
},
],
}
renderHead = (item) => {
return(
<Text style={{ fontSize: 18, fontWeight: '600' }}>
{item.title}
</Text>
);
}
renderBody = (item) => {
return (
<View style={{padding:10, backgroundColor: '#e3e3e3'}}>
{item.data.map(something => (
<Text>{something.name}</Text>
))}
</View>
);
}
render() {
const { data } = this.state;
return (
<View style={styles.container}>
<AccordionList
list={data}
header={this.renderHead}
body={this.renderBody}
/>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
},
});
关于javascript - 如何在 Accordion react 原生中渲染复杂对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59193503/