2017-02-13 90 views
0

我有以下代碼,這是很好,工作,但我看我如何能更好地生產這樣幹,如果我可以結合所有的定製等,將是王牌反應本地幹條件語句

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
_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> 
+0

我是否需要傳遞任何參數? –

+0

要麼'牛奶'或'尺寸' – binchik

+0

所以我怎麼實際上傳遞這個參數到這個代碼? –