通过使用样式化组件,如何为来自外部道具的背景颜色添加一些不透明度



这是我的代码,在它下面你会发现问题

import { printIntrospectionSchema } from 'graphql';
import React, { useContext, useState } from 'react';
import styled from 'styled-components';
import { Context } from '../../../Context/Context';
// DATA
function DurationIntervalSelection() {
const tabsData = [
{
text: 'Duration',
},
{
text: 'Interval',
},
];
// STATE
const [selectedIndex, setselectedIndex] = useState(0);
const { selected } = useContext(Context);
console.log(selected.color, 'selected color');
// FUNCTION
const handleIndexSelection = (index) => {
setselectedIndex(index);
};
return (
<Container>
<TabsContainer backgroundColor={selected.backgroundColor}>
<Indicator
backgroundColor={selected.color}
style={{
left: `${selectedIndex * 50}%`,
}}
/>
{tabsData.map((tab, index) => {
return (
<Tab
style={{
color: selectedIndex === index ? 'white' : 'black',
}}
onClick={() => handleIndexSelection(index)}
key={tab.text}
>
<p style={{ zIndex: 100 }}>{tab.text}</p>
</Tab>
);
})}
</TabsContainer>
</Container>
);
}
const Container = styled.div`
margin-top: 10px;
border: 1px solid #f2f2f7;
border-radius: 10px;
box-sizing: border-box;
padding: 10px 0;
`;
const Indicator = styled.div`
width: 50%;
position: absolute;
/* z-index: -1; */
height: 100%;
border-radius: 20px;
cursor: pointer;
transition: all 0.3s;
background-color: ${(props) => props.backgroundColor};
`;
const TabsContainer = styled.div`
display: flex;
width: 100%;
justify-content: space-between;
position: relative;
box-shadow: 1px 1px 3px rgba(0, 0, 0, 0.2);
border-radius: 20px;
overflow: hidden;
background-color: ${(props) => props.backgroundColor};
`;
const Tab = styled.div`
display: flex;
width: 50%;
justify-content: center;
cursor: pointer;
align-items: center;
padding: 10px;
`;
export default DurationIntervalSelection;

正如你从上面的代码中看到的,我将backgroundColor作为一个道具传递,它从React状态中获取一些颜色。

<TabsContainer backgroundColor={selected.backgroundColor}>

在我做的样式组件中:

背景颜色:${(props(=>props.backgroundColor};

但我的问题是,由于我需要遵循同事的设计,我如何在不影响整个div的不透明度的情况下为上面的背景色添加不透明度:TabsContainer。我的意思是,如果我加上TabsContainer->opacity:0.3-例如,整个TabsContainerdiv将受到不透明度的影响,包括Tabdiv,而我想要的只是改变颜色本身的不透明度,这样我就不会影响任何子项。我希望这是有道理的。有办法吗?

好吧,如果您的十六进制值来自后端,您可以创建自己的javascript函数,将十六进制转换为rgba,也可以使用类似抛光的库。他们有一个名为rgba的函数,可以转换十六进制字符串并向其添加一个阿尔法值

import { rgba } from 'polished'
const div = styled.div`
background: ${(props) => rgba(props.backgroundColor, 0.3)};
`

或者你可以直接将其应用于道具

<TabsContainer backgroundColor={rgba(selected.backgroundColor, 0.3)}>

示例CodeSandbox。

由于来自后端的数据是正确的,但我找不到解决方案,我意识到我本可以添加到

<TabsContainer backgroundColor="rgba(255,255,255, 0.5)">

白色音符上的背景色带有不透明度,以便以较浅的方式强调其背后的颜色

最新更新