我有以下一段代码,这些代码都很好并且正常工作,但是我正在研究如何更好地制作这个代码,以便它干,如果我可以将所有自定义等组合起来就是ace
render() {
let sizeHeader,milkHeader = null;
this.props.data.size ? sizeHeader = <Text style={styles.headerLabel}>Size</Text> : null
this.props.data.milk ? milkHeader = <Text style={styles.headerLabel}>Milk</Text> : null
return (
<View style={styles.container}>
<ParallaxScrollView>
<View>
{sizeHeader}
{(this.props.data.size||[]).map((section,i) => (
<AddToCartRow key={i} data={section} productName={this.props.data.name} value={Config.priceToPriceWithCurrency(section.price)} />
))}
{milkHeader}
{(this.props.data.milk||[]).map((section,i) => (
<AddToCartRow key={i} data={section} productName={this.props.data.name} value={Config.priceToPriceWithCurrency(section.price)} />
))}
</View>
</ParallaxScrollView>
<RoundedButton onPress={()=>{NavigationActions.CartAndCheckout()}}>
Go to Cart
</RoundedButton>
</View>
);
}
JSON
{
"Merchants" : {
"items" : [ {
"address" : "address here",
"items" : [ {
"description" : "Silky frothed milk poured over a shot of espresso, topped with a touch of chocolate.",
"info" : {
"Calories" : "250 kcal",
"Glutten Free" : "Yes"
},
"milk" : [ {
"name" : "Full Cream",
"price" : 0
}, {
"name" : "Almond",
"price" : ".5"
}, {
"name" : "Coconut",
"price" : ".5"
}, {
"name" : "Soy",
"price" : ".5"
}, {
"name" : "Cunt",
"price" : 5
} ],
"name" : "Cappuccino",
"photo" : "https://upload.wikimedia.org/wikipedia/commons/e/ed/Wet_Cappuccino_with_heart_latte_art.jpg",
"price" : 10.0,
"size" : [ {
"name" : "Small",
"price" : 10
}, {
"name" : "Medium",
"price" : 18
} ]
}
答案 0 :(得分:0)
_renderContent = (key) => (
<View>
{this.props[key] && <Text style={styles.header}>{`${key.charAt(0).toUppercase()}${key.slice(1)}`}</Text>}
{(this.props[key] || []).map(section, i) => (
<AddToCartRow
key={i}
data={section}
productName={this.props.data.name}
value={Config.priceToPriceWithCurrency(section.price)}
/>
)}
</View>
);
您应该传递要映射的props
密钥。
<ParallaxScrollView>
<View>
{['milk', 'size'].map(this._renderContent)}
</View>
</ParallaxScrollView>