2017-03-23 47 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

相关问题