- 今天遇到这么一个需求: 后端返回了一个按钮数据的list,数据格式如下,但是设计图给的样式是背景色有透明度显示的,所以这边将十六进制的颜色转换成rgba形式
let data = [
{ btnId: 1, name: '按钮1', color: "#3f6da7" },
{ btnId: 2, name: '按钮2', color: "#5ada7" },
{ btnId: 3, name: '按钮3', color: "#ef6d47" },
{ btnId: 4, name: '按钮4', color: "#a7a7a7" },
]
demo示例
import React from 'react'
class Test extends React.Component {
constructor(props) {
super(props)
this.state = {}
}
hexToRgba = (hex, opacity) => {
return 'rgba(' + parseInt('0x' + hex.slice(1, 3)) + ',' + parseInt('0x' + hex.slice(3, 5)) + ','
+ parseInt('0x' + hex.slice(5, 7)) + ',' + opacity + ')';
}
render() {
const color = "#a0c3d8"
const styles = {
width: '200px',
height: '300px',
}
let data = [
{ btnId: 1, name: '按钮1', color: "#3f6da7" },
{ btnId: 2, name: '按钮2', color: "#5ada7" },
{ btnId: 3, name: '按钮3', color: "#ef6d47" },
{ btnId: 4, name: '按钮4', color: "#a7a7a7" },
]
const btnItem = {
height: "40px",
lineHeight:'40px',
borderRadius: "20px",
padding: '0 15px',
marginBottom: "20px"
}
return (
<div style={{ background: this.hexToRgba(color, 0.05), ...styles }}>
{data.map(item => <div className="btnItem" style={{ background: this.hexToRgba(item.color, 0.1), ...btnItem }}>{item.name}</div>)}
</div>
)
}
}
export default Test
核心转换代码
hexToRgba = (hex, opacity) => {
return 'rgba(' + parseInt('0x' + hex.slice(1, 3)) + ',' + parseInt('0x' + hex.slice(3, 5)) + ','
+ parseInt('0x' + hex.slice(5, 7)) + ',' + opacity + ')';
}
```