2017-03-16 3 views
0

私はReactJSを初めて使っています。 ProductInfoは、ユーザーが情報を記入できるプロジェクト内のカードです。 ReactJSコードのProduct const内に条件を設定したい:レンダリングされたアイテムの数に応じて、特定のブートストラップクラスの条件でreactJS?

ここで2つのProductInfoカードしか記入されていない場合は、class-nameにcol-md-6を適用して2枚のカードが2つ以上のProductInfoカードが記入されている場合は、col-md-4を使用してください。これをどうやってやりますか?

const ProductInfo = ({ title, blurb }) => (
    <div> 
     {title && <h3 className="color-accent">{title}</h3>} 
     {blurb && 
      <span dangerouslySetInnerHTML={{__html: productBlurb}} /> 
     } 
    </div> 
); 

const Product = (props) => (
//If only two ProductInfo cards are present, apply a boostrap class of col-md-6, otherwise apply the bootstrap class below 
    <div className="hs-product col-xs-12 col-sm-12 col-md-4" > 
     {props.productIconLink ? 
      <a href={props.link} target="_blank"> 
       <ProductInfo {...props} /> 
      </a> 
     : 
      <ProductInfo {...props} /> 
     } 
    </div> 
); 

答えて

0

ProductInfoデータをProps経由でProductに渡すことをお勧めします。

const ProductInfoData = [ 
{ 
    title: 'title1', 
    blurb: 'blurb1' 
}, 
{ 
    title: 'title2', 
    blurb: 'blurb2' 
}, 
... 
] 

この方法を使用すると、配列をマップして各ProductInfoをレンダリングできます。 props.productInfoData.lengthを使用して、レンダリングするProductInfoコンポーネントの数を知ることさえできます。

const Product = (props) => { 
    const className = 'hs-product col-xs-12 col-sm-12 ' + this.props.productInfoData.length == 2 ? 'col-md-6' : 'col-md-4'; 
    return (
     <div className={className}> 
      {this.props.productInfoData.map((data) => { 
       if (this.props.productIconLink) { 
        return (
         <a href={props.link} target="_blank"> 
          <ProductInfo {...data} /> 
         </a> 
        ) 
       } else return <ProductInfo {...data} />; 
      })} 
     </div> 
    ); 
}; 

これは、あなたが<Product />をレンダリングする方法を次のとおりです:

また
const ProductInfoData = [ 
    { 
     title: 'title1', 
     blurb: 'blurb1' 
    }, 
    ... 
] 

<Product productInfoData={ProductInfoData} /> 

私があなただったら、私はdangerouslySetInnerHTMLを使用して回避するあなたは、このような何かを行うことができます。通常はこれを使用する必要はなく、必要がないようにコンポーネントを書き換えることができます。

関連する問題