【问题标题】:React styled component child prop selectorReact 样式的组件子属性选择器
【发布时间】:2020-05-11 06:51:28
【问题描述】:

是否可以在样式组件中为子组件道具制作选择器?

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

我想像这样访问道具:

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

有可能吗,如果可以,我应该怎么做?

【问题讨论】:

    标签: javascript reactjs styled-components


    【解决方案1】:

    您正在尝试使用Attribute selectors,因此您需要在Checkbox 组件上定义有效属性,例如data-*

    如果您尝试使用组件的属性,则必须提升状态(参见 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>
      );
    };
    

    【讨论】:

    • 谢谢!您会推荐哪种方法?我想要解除状态,我需要在 Accordion 组件之外定义方法,这将使其不可重用,并且每次实现手风琴时我都需要复制该方法,对吗?
    • 没有“更好”的方法,状态是动态的,选择适合您的用例。
    猜你喜欢
    • 2017-10-05
    • 2016-07-21
    • 2014-09-27
    • 2012-01-15
    • 1970-01-01
    • 2018-10-06
    • 2019-02-18
    • 1970-01-01
    • 2021-06-01
    相关资源
    最近更新 更多