[英]Styled components styles overridden when using props
I have the following styled components我有以下样式的组件
const Test1 = styled.div`
// some styles
`;
const Test2 = styled.div`
background-color: ${({ someProp }) => someProp ? "cyan" : "magenta"};
${Test1} > & {
color: ${({ someProp }) => someProp ? "red" : "green"};
}
`;
I'm using these components like this我正在像这样使用这些组件
<Test2 someProp>Test2 (bg: cyan, color: black)</Test2>
<Test2>Test2 (bg: magenta, color: black)</Test2>
<Test1>
<Test2 someProp>Inner Test2 (bg: cyan, color: red)</Test2>
<Test2>Inner Test2 (bg: magenta, color: green)</Test2>
</Test1>
The HTML output is this HTML output是这里
<div class="pages__Test2-doZfs hsqqBA">Test2 (bg: cyan, color: black)</div>
<div class="pages__Test2-doZfs iQIEMM">Test2 (bg: magenta, color: black)</div>
<div class="pages__Test1-ifSjDr">
<div class="pages__Test2-doZfs hsqqBA">Inner Test2 (bg: cyan, color: red)</div>
<div class="pages__Test2-doZfs iQIEMM">Inner Test2 (bg: magenta, color: green)</div>
</div>
The styles output that I would expect is this我期待的styles output是这个
<style>
.hsqqBA {
background-color: cyan;
}
.pages__Test1-ifSjDr > .hsqqBA {
color: red;
}
.iQIEMM {
background-color: magenta;
}
.pages__Test1-ifSjDr > .iQIEMM {
color: green;
}
</style>
But what I'm actually getting is this但我实际上得到的是这个
<style>
.hsqqBA {
background-color: cyan;
}
.pages__Test1-ifSjDr > .pages__Test2-doZfs {
color: red;
}
.iQIEMM {
background-color: magenta;
}
.pages__Test1-ifSjDr > .pages__Test2-doZfs {
color: green;
}
</style>
So, this is causing the third Test2 instance to have a color green instead of red.因此,这导致第三个 Test2 实例的颜色为绿色而不是红色。
My question is why does this happen and more importantly what can I do to handle this?我的问题是为什么会发生这种情况,更重要的是我能做些什么来处理这个问题?
Thanks谢谢
Well, after reading online I found that all I needed to do was to use &&
instead of &
when using props within a reference to other components好吧,在网上阅读后我发现我需要做的就是在引用其他组件时使用
&&
而不是&
当使用 props 时
const Test1 = styled.div`
// some styles
`;
const Test2 = styled.div`
background-color: ${({ someProp }) => someProp ? "cyan" : "magenta"};
${Test1} > && {
color: ${({ someProp }) => someProp ? "red" : "green"};
}
`;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.