这是我的代码,在它下面你会找到问题
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作为一个 Prop 传递,它从React状态中获取一些颜色。
<TabsContainer backgroundColor={selected.backgroundColor}>
在样式组件中我这样做:
背景颜色:${(props) => props.backgroundColor};
但我的问题是,由于我需要遵循同事的设计,如何在不影响整个div的不透明度的情况下为上面的背景颜色添加不透明度:TabsContainer。我的意思是,如果我添加 TabsContainer -> opacity: 0.3 - 例如整个 TabsContainer div 将受到不透明度的影响,包括 Tab div,而我想要的只是更改颜色本身的不透明度,所以我不这样做影响任何一个 child 。我希望这是有道理的。有办法吗?
最佳答案
好吧,如果您的十六进制值来自后端,您可以创建自己的将十六进制转换为 rgba 的 javascript 函数,也可以使用像 polished 这样的库。 。他们有一个名为 rgba 的函数,可以转换十六进制字符串并向其添加 alpha 值
import { rgba } from 'polished'
const div = styled.div`
background: ${(props) => rgba(props.backgroundColor, 0.3)};
`
或者你可以直接将其应用到 Prop
<TabsContainer backgroundColor={rgba(selected.backgroundColor, 0.3)}>
关于reactjs - 通过使用样式化组件,如何为来自外部 Prop 的背景颜色添加一些不透明度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70308572/