2017-02-13 5 views
0

J'ai le morceau de code suivant qui est tout bien et fonctionne, mais je regarde comment je peux mieux produire ceci si son DRY, si je peux combiner toutes les personnalisations etc. seraitréagir natif condition conditionnelle sèche

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 
     } ] 
     } 

Répondre

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> 
); 

vous devriez passer la clé de props que vous souhaitez mapper.

<ParallaxScrollView> 
    <View> 
    {['milk', 'size'].map(this._renderContent)} 
    </View> 
</ParallaxScrollView> 
+0

dois-je lui transmettre des arguments? –

+0

Soit 'milk' ou' size' – binchik

+0

alors comment transmettre ces arguments à ce code? –