我一直在尝试为我的背景图像设置一个不透明度,但不透明度唯一改变的基本上是图像旁边的所有东西。如何使用样式化组件更改主体的属性?
import styled, { createGlobalStyle } from "styled-components";
import Clouds from "./Pics/Clouds.png";
const GlobalStyle = createGlobalStyle`
body {
background-image: url(${Clouds});
}
`;
const StyledText = styled.div`
text-align: justify;
position: fixed;
top: 50%;
left: 50%;
margin-top: -50px;
margin-left: -100px;
font-size: 35px;
font-family: "Comic Sans MS";
`;
const Weather = (props) => {
return (
<React.Fragment>
{" "}
<StyledText>
Today : {props.main}
<br />
City : {props.city}
<br />
Celcius: {props.temp}
<br />
</StyledText>
<GlobalStyle />
</React.Fragment>
);
};
export default Weather;
谢谢你的任何帮助!
我不是很确定你想在哪个元素上设置不透明度。但是,有趣的是,您可以在呈现您的样式组件时传递道具,并在您的样式组件定义中捕获它们。
首先,在div中定义图像组件。
const StyledImage = styled.div`
background-image: url("example.jpg")
opacity: ${props => props.imgOpacity}
`;
调用%s时。组件时,可以设置不透明度:
<StyledImage imgOpacity={"0.5"} />
使用道具是为您的样式化组件重用样式并防止样式干扰其他元素的一种很酷的方式。
你不能在背景属性上设置不透明度,你有两个选项,就我所见,要么你使用一个已经“不透明度”的图像,要么你使用一个不同的组件/元素作为背景,然后把不透明度添加到元素本身,就像下面的例子
import styled, { createGlobalStyle } from "styled- components";
import Clouds from "./Pics/Clouds.png";
const YourBg = styled.div `
background-image: url(${Clouds});
opacity: 0.5;
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
`;
const StyledText = styled.div`
text-align: justify;
position: fixed;
top: 50%;
left: 50%;
margin-top: -50px;
margin-left: -100px;
font-size: 35px;
font-family: "Comic Sans MS";
`;
const Weather = (props) => {
return (
<React.Fragment>
{" "}
<YourBg />
<StyledText>
Today : {props.main}
<br />
City : {props.city}
<br />
Celcius: {props.temp}
<br />
</StyledText>
</React.Fragment>
);
};
export default Weather;