2017-03-23 1 views
3

ドキュメントの例では同じファイルに表示されています(https://facebook.github.io/react/docs/thinking-in-react.html)。すべての反応成分は個々のファイルにあるべきですか?

コンポーネントの一部が非常に小さいこのようなインスタンスで、コンポーネントをページに分割するとどうでしょうか?

class ProductCategoryRow extends React.Component { 
    render() { 
    return (<tr><th colSpan="2">{this.props.category}</th></tr>); 
    } 
} 

class ProductRow extends React.Component { 
    render() { 
    var name = this.props.product.stocked ? 
     this.props.product.name : 
     <span style={{color: 'red'}}> 
     {this.props.product.name} 
     </span>; 
    return (
     <tr> 
     <td>{name}</td> 
     <td>{this.props.product.price}</td> 
     </tr> 
    ); 
    } 
} 

class ProductTable extends React.Component { 
    render() { 
    var rows = []; 
    var lastCategory = null; 
    this.props.products.forEach((product) => { 
     if (product.name.indexOf(this.props.filterText) === -1 || (!product.stocked && this.props.inStockOnly)) { 
     return; 
     } 
     if (product.category !== lastCategory) { 
     rows.push(<ProductCategoryRow category={product.category} key={product.category} />); 
     } 
     rows.push(<ProductRow product={product} key={product.name} />); 
     lastCategory = product.category; 
    }); 
    return (
     <table> 
     <thead> 
      <tr> 
      <th>Name</th> 
      <th>Price</th> 
      </tr> 
     </thead> 
     <tbody>{rows}</tbody> 
     </table> 
    ); 
    } 
} 

答えて

2

あなたは、独自のファイル内の各コンポーネントを配置する必要がないかもしれません - 例えば、あなたはさらにステートレス機能コンポーネントを使用してProductRowコンポーネントを分割することができます:

const ProductName = (product) => 
    <span style={{color: product.stocked ? 'black' : 'red'}}> 
    { product.name } 
    </span> 

const ProductRow = (product) => 
    <tr> 
    <td>{ ProductName(product) }</td> 
    <td>{ product.price }</td> 
    </tr> 
+0

をありがとう!個々のファイルを何にするべきか、何をすべきではないのかに関する一般的なガイドラインはありますか? Reactクラスは一般に個々のファイルですか? – Aspen

+2

一般に、再利用可能なコンポーネントは独自のファイルに格納されますが、特定の目的のために相互に依存するコンポーネントは同じファイルに格納されます – Brian

関連する問題