遇到后端返回数据为颜色+数值对象,需求是先照数字大小排序,再根据颜色生成渐进色带
{ "#00C864": 26, "#FFB400": 6, "#0064C8": 32, "#64C800": 13, "#FF0000": 0, "#64C864": 19 }
先进行排序,
this.colorList={
"#00C864": 26,
"#FFB400": 6,
"#0064C8": 32,
"#64C800": 13,
"#FF0000": 0,
"#64C864": 19
}
// 排序函数
sortArray= array => {
return function (obj1,obj2) {
var value1=obj1[array];
var value2=obj2[array];
if(value1<value2){
return -1
}else if(value1>value2){
return 1
}else {
return 0
}
}
}
let theColorList=[]
//用来保存颜色字符串
let colors=''
setColorList = () => {
for(let key in this.colorList){
theColorList.push(
{
color:key,
num:this.colorList[key]
}
)
}
//调用排序函数
this.cloudColorList.sort(this.sortArray('num'))
this.cloudColorList.map(
(item,index) => {
colors.push(item.color)
}
)
this.setState({
colorList:this.cloudColorList,
//将排好序的颜色转为字符串
colorString:colors.toString()
})
}
然后生成结构题
<div>
<div
style={{width:'500px',height:'20px',background:`linear-gradient(to
right,${this.state.colorString})`}}
></div>
{
this.colorList.map(
(item,index) => {
return(
<i
key={index}
style={{marginRight:'56px',fontSize:'12px'}}
>
{item.num}
</i>
)
}
)
}
</div>
最后看下效果吧
希望能帮助到正在想怎么弄的小伙伴,如果有错误或者更好的建议可以留言,谢谢!