2016-09-10 79 views
0

我的代碼更清潔的方式如下:寫ReactJS組件

import React, {PropTypes} from 'react'; 
import ReactCSSTransitionGroup from 'react-addons-css-transition-group'; 
import { filter_names } from './filterActions'; 
import Price from './price'; 
import Year from './year'; 
import Make from './make'; 
import Model from './model'; 
import Mileage from './mileage'; 
import Transmission from './transmission'; 
import Fuel from './fuel'; 

class filters extends React.Component { 

    showFilters(filters){ 

     return filters.map(filter => { 
      switch (filter.name){ 
       case filter_names.priceRange: 
        return <Price recap={filters.some(f => f.name === filter_names.priceRange)} title="Price" filters={filters} {...this.props}/>; 
       case filter_names.year: 
        return <Year recap={filters.some(f => f.name === filter_names.year)} title="Year" filters={filters} {...this.props}/>; 
       case filter_names.mileage: 
        return <Mileage recap={filters.some(f => f.name === filter_names.mileage)} title="Mileage" filters={filters} {...this.props}/>; 
       case filter_names.fuel: 
        return <Fuel recap={filters.some(f => f.name === filter_names.fuel)} title="Fuel" filters={filters} {...this.props}/>; 
       case filter_names.transmission: 
        return <Transmission recap={filters.some(f => f.name === filter_names.transmission)} title="Transmission" filters={filters} {...this.props}/>; 
       default: 
        return true; 
      } 
     }) 
    } 


    render(){ 
     const language = this.props.language; 
     const filters = this.props.filters; 

     return (
      <div className="filters noPadding col-xl-8 col-lg-6 col-md-6 col-sm-5 col-xs-12"> 
       <ReactCSSTransitionGroup transitionName="example" transitionAppear={true} transitionAppearTimeout={500} transitionEnterTimeout={500} transitionLeaveTimeout={500}> 
        {this.showFilters(filters)} 
       </ReactCSSTransitionGroup> 
      </div> 
     ); 
    } 

} 

export default filters; 

有沒有辦法把它寫在一個更清潔的方式?我在showFilter中使用了所有這些組件。我是否需要爲每個組件重複它,或者有沒有更簡單的方法來完成它?

+0

我覺得您應該是更具體的瞭解您所要實現的目標,或那麼這應該被移動到http://codereview.stackexchange.com/ – Waiski

回答

-1

的過濾器創建一個基類:

class BaseFilter extends React.Component { 
    showFilters(filters){  
    } 
} 

派生您所有過濾器類從BaseFilter:

class AnotherFilter extends BaseFilter { 
    render() { 
    } 
} 
+0

這並不能解決他們的問題(另外,在React中使用繼承通常是一個壞主意)。他們不希望每個組件都可以訪問'showFilters',他們希望根據該功能的結果顯示一組不同的子組件。 –

+0

反應比繼承更喜歡構圖。繼承不會簡化代碼,只能將其隱藏在子類中 –

+0

我錯了!我的印象是有很多Filter組件有一些常用的方法。我遇到了一些基類有意義的場景。 – vijayst