我使用Babel和ES6语法使用React编写指标组件,并为使用CSS模块的组件设置样式。该组件工作正常,但我想提高我的代码质量。
在指标的每个状态中,点的颜色都会改变。
import React from 'react'
import ClassNames from 'classnames'
import styles from './Indicator.css'
const Indicator = (props) => {
const { current, number, enabled } = props
if (enabled) {
const dots = []
for (var i = 0; i < number; i++) {
// FIXME: It must be a better way to implement this
let dotStyles = ClassNames(styles.dot, {
[styles.red]: current === i && i === 0,
[styles.orange]: current === i && i === 1,
[styles.yellow]: current === i && i === 2,
[styles.green]: current === i && i === 3,
[styles.gray]: current !== i
})
dots.push(<div className={dotStyles} key={i} />)
}
return <div className={styles.indicator}>{dots}</div>
} else {
return <div />
}
}
const { number, bool } = React.PropTypes
Indicator.propTypes = {
number: number,
current: number,
enabled: bool
}
export default Indicator
定义样式的CSS使用CSS模块和组合关键字
.indicator {
display: flex;
flex-direction: row;
align-items: center;
height: 12px;
margin-bottom: 40px;
}
.dot {
width: 12px;
height: 12px;
margin-left: 10px;
border-radius: 6px;
}
.gray { composes: gray from '../../colors.css'; }
.red { composes: red from '../../colors.css'; }
.orange { composes: orange from '../../colors.css'; }
.yellow { composes: yellow from '../../colors.css'; }
.green { composes: green from '../../colors.css'; }
我对这种方法有两个问题:
我一直在研究react-css-modules,但到目前为止,我认为我不介意在代码中使用styles.class。
答案 0 :(得分:0)
我最终使用react-css-modules包来优化代码。
const dots = []
for (var i = 0; i < number; i++) {
const dotClassList = ['red-dot', 'orange-dot', 'yellow-dot', 'green-dot']
const dotClass = (current === i) ? dotClassList[i] : 'gray-dot'
dots.push(<div styleName={dotClass} key={i} />)
}
return <div styleName='indicator'>{dots}</div>
我还使用了compose模式,只有一个类避免使用ClassName包。
.indicator {
display: flex;
flex-direction: row;
align-items: center;
height: 12px;
margin-bottom: 40px;
}
.dot {
width: 12px;
height: 12px;
margin-left: 10px;
border-radius: 6px;
}
.gray-dot {
composes: gray from '../../colors.css';
composes: dot;
}
.red-dot {
composes: red from '../../colors.css';
composes: dot;
}
.orange-dot {
composes: orange from '../../colors.css';
composes: dot;
}
.yellow-dot {
composes: yellow from '../../colors.css';
composes: dot;
}
.green-dot {
composes: green from '../../colors.css';
composes: dot;
}
欢迎提出其他建议!