[英]Styled components styles overridden when using props
我有以下樣式的組件
const Test1 = styled.div`
// some styles
`;
const Test2 = styled.div`
background-color: ${({ someProp }) => someProp ? "cyan" : "magenta"};
${Test1} > & {
color: ${({ someProp }) => someProp ? "red" : "green"};
}
`;
我正在像這樣使用這些組件
<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>
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>
我期待的styles output是這個
<style>
.hsqqBA {
background-color: cyan;
}
.pages__Test1-ifSjDr > .hsqqBA {
color: red;
}
.iQIEMM {
background-color: magenta;
}
.pages__Test1-ifSjDr > .iQIEMM {
color: green;
}
</style>
但我實際上得到的是這個
<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>
因此,這導致第三個 Test2 實例的顏色為綠色而不是紅色。
我的問題是為什么會發生這種情況,更重要的是我能做些什么來處理這個問題?
謝謝
好吧,在網上閱讀后我發現我需要做的就是在引用其他組件時使用&&
而不是&
當使用 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.