[英]How to render an complex object in accordion react-native
我有一個像這樣的復雜對象:
{
"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
}
]
}
我想在來自這里的 Collaseable 組件中呈現它: https ://www.npmjs.com/package/accordion-collapse-react-native
我希望它在 CollapseHeader 組件和 CollapseBody 組件中呈現“熱食”、“冷飲”,我想一一呈現這些對象數組。
但我無法弄清楚,因為我不太擅長 javascript 並且它不是我的核心語言。我只需要在本機應用程序中以這種方式呈現它。
任何幫助或想法都會受到重視,我在互聯網上找不到任何完全相同的示例。
在這里,讓我向您展示我正在嘗試的功能:
{
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,
},
});
訪問此鏈接查看小吃: https : //snack.expo.io/@iamshadmirza/556cf0
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.