简体   繁体   English

React 样式的组件子属性选择器

[英]React styled component child prop selector

is it possible to make selector for child component prop in styled components?是否可以在样式组件中为子组件道具制作选择器?

<Accordion>
   <Checkbox checked='false' />
   <Text>Text to be hidden when checked is false</Text>
</Accordion>

I would like to access the prop something like this:我想访问这样的道具:

const Accordion = styled.div`
    & > ${Checkbox}[checked='false'] ~ ${Text} {
        display: none;
    }
`;

Is it possible and if so, how should I do it?有可能吗?如果可以,我该怎么做?

You are trying to use Attribute selectors , so you need to define valid attributes on Checkbox component like data-* .您正在尝试使用Attribute selectors ,因此您需要在Checkbox组件上定义有效属性,例如data-*

If you trying to use component's property, you have to lift the state up (see Text with "State from Parent").如果您尝试使用组件的属性,则必须将 state 抬起(请参阅带有“来自父级的状态”的Text )。

const Checkbox = styled.div``;
const Text = styled.div``;

const Accordion = styled.div`
  & > ${Checkbox}[data-checked="true"] ~ ${Text} {
    color: palevioletred;
    font-weight: 600;
    &:last-child {
      color: ${prop => (prop.checked ? `blue` : `orange`)};
    }
  }
  & > ${Text}[title="example"]{
    border: 1px solid black;
  }
`;

const App = () => {
  return (
    <Accordion checked>
      <Checkbox data-checked="true" checked="true">
        I'm Check box
      </Checkbox>
      <Text title="example">With attr gives border</Text>
      <Text>Without attr</Text>
      <Text>State from Parent</Text>
    </Accordion>
  );
};

编辑 quiet-tree-lnukc

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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