简体   繁体   中英

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

<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

<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.

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

const Test1 = styled.div`
  // some styles
`;

const Test2 = styled.div`
  background-color: ${({ someProp }) => someProp ? "cyan" : "magenta"};

  ${Test1} > && {
    color: ${({ someProp }) => someProp ? "red" : "green"};
  }
`;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM