简体   繁体   English

将道具传递给样式组件选择器

[英]pass props to styled-components selector

I've got a styled-component which gets some additional styles based on a property (active).我有一个样式组件,它根据属性(活动)获得一些额外的 styles。

The component looks similar to this:该组件看起来类似于:

import styled from 'styled-components';

const Button = styled.button`
  color: black;

  ${props => props.active ? `color: red;` : ''}
`;

Within a component test I need to select the active Button which (obviously) doesn't work doing the following:在组件测试中,我需要 select 活动按钮,它(显然)在执行以下操作时不起作用:

document.querySelector(Button)

since this targets all Button components, no matter if active or not.因为这针对所有 Button 组件,无论是否处于活动状态。

I read the styled-components docs and googled a lot.我阅读了 styled-components 文档并在谷歌上搜索了很多。 However I haven't been able to find a way to pass specific props to the styled-components-selector.但是我一直无法找到将特定道具传递给样式化组件选择器的方法。 I expected something similar to the following (which does not work)我期望类似于以下内容(不起作用)

document.querySelector(Button({ active: true }))

Is there any way to achieve this or rather how do you select a styled component which has specific props?有什么办法可以做到这一点,或者更确切地说,您如何 select 具有特定道具的样式化组件?

I think I've found a solution which is probably the 'right' way when using styled-components.我想我找到了一个解决方案,这可能是使用样式组件时的“正确”方式。

Instead of defining the active style via props within the button component, I've created another one which extends the button.我没有通过按钮组件中的道具定义活动样式,而是创建了另一个扩展按钮的样式。 This of course forces me to use another component for the active button instead of just setting an active property.这当然迫使我为活动按钮使用另一个组件,而不仅仅是设置活动属性。

However it's not much additional work and super easy to test.然而,它并没有太多额外的工作,而且非常容易测试。 So I've decided to go this way.所以我决定用这种方式 go 。

const Button = styled.button`
  color: black;
`;

const ActiveButton = styled(Button)`
  color: red;
`;

document.querySelector(ActiveButton);

The correct syntax is this:正确的语法是这样的:

const Button = styled.button`
  color: black;
  color: ${props => props.active ? 'red' : ''};
`;

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

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