【问题标题】:Specific targeting of CSS classes with Styled Components not being rendered - React未呈现样式化组件的 CSS 类的特定目标 - React
【发布时间】:2021-11-02 04:31:57
【问题描述】:

一段时间以来,我一直在为样式问题苦苦挣扎,但基本问题是我想在第一个之后对<StyledButton> 的每个实例进行不同的样式设置。为此,我的目标是包装元素 (attributeset-row className) 和 remove-btn className (for <StyledButton>),如下所示:

const StyledHorizontalAttributesTable = styled(StyledHorizontalAttributes)`
  & .attributeset-row:not(:first-child) .remove-btn {
    background-color: lightblue;
  }
`;

我发现问题在于 CSS 样式没有应用于组件,因为我的目标是 classNames - 正如您在下面看到的那样,我将 classNames 传递给相关组件(并且它们显示在浏览器中),但还有很多其他看起来像是行话的东西:

谁能解释我在向 StyledComponents 应用特定的 CSS 样式时可能会出错的地方(通常不需要这种类型的样式),但我需要在第一个不同的样式之后为所有 StyledButton> 设置样式.

这是我的代码:

const StyledButton = styled(Button)`
  margin-top: 14px;
`;

const StyledHorizontalAttributesTable = styled(StyledHorizontalAttributes)`
  & .attributeset-row:not(:first-child) .remove-btn {
    background-color: lightblue;
  }
`;

  return (
    <div className={className}>
      {objects.map((enteredObject, index) => (
        <RepeatableAttributeSetContextProvider
          form={form}
          object={enteredObject}
          key={`${enteredObject.key}-${enteredObject.repeatIndex}`}
        >
          <StyledHorizontalAttributesTable className="attributeset-row">
            {enteredObject.attributeCollection.questions
              .filter(filterRepeatAttributes)
              .map((attribute) => (
                <Fragment key={attribute.key}>
                  {renderAttribute(enteredObject, attribute, formLayout)}
                </Fragment>
              ))}
            <StyledButton
              className="remove-btn"
              type="link"
              buttonStyle="LINK"
              name="delete"
              dataId={`delete-${enteredObject.key}-${index}`}
              isOberonIcon
              isIconButton
              icon="bin"
              onClick={() => onRemove(enteredObject)}
            >
              <Message id="Form.Button.Remove" defaultMessage="Remove" />
            </StyledButton>
          </StyledHorizontalAttributesTable>
        </RepeatableAttributeSetContextProvider>
      ))}
    </div>
  );

【问题讨论】:

    标签: javascript css reactjs css-selectors styled-components


    【解决方案1】:

    我会使用相邻的兄弟组合器。这将针对除第一个.attributeset-rows 之外的所有.attributeset-rows。

    const StyledHorizontalAttributesTable = styled(StyledHorizontalAttributes)`
      & + & {
        .remove-btn {
          background-color: lightblue;
        }
      }
    `;
    

    这是 CodeSandbox 上此示例的简单版本。 https://codesandbox.io/s/serene-swanson-frcb4?file=/src/App.js

    【讨论】:

      猜你喜欢
      • 2017-12-31
      • 2021-06-07
      • 2020-11-17
      • 2021-01-29
      • 1970-01-01
      • 2017-05-04
      • 1970-01-01
      • 2017-11-11
      相关资源
      最近更新 更多