我的代碼更清潔的方式如下:寫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中使用了所有這些組件。我是否需要爲每個組件重複它,或者有沒有更簡單的方法來完成它?
我覺得您應該是更具體的瞭解您所要實現的目標,或那麼這應該被移動到http://codereview.stackexchange.com/ – Waiski