如何在样式化组件之外设置样式?

Posted

技术标签:

【中文标题】如何在样式化组件之外设置样式?【英文标题】:How to set styles outside of the styled component? 【发布时间】:2021-10-21 23:50:10 【问题描述】:

我确定,有办法解决这个问题,但我找不到。 我有一个反应组件GenericList,它是一个具有 CRUD 功能的列表。它内部有自己的Popup

<GenericList
  popupContent=(
    <CharterPeriodsPopup
      charter=charter
    />
  )

这是 GenericList 中的代码

<Popup
  bodyClassName=this.props.bodyClassName
  contentClassName=this.props.contentClassName
  title=title
  ...this.props.popupProps
>
  !popupContent ? '$popupContent': (
           cloneElement(this.props.popupContent, ...popupProps))
</Popup>

我想访问 GenericList 中的 Popup 并通过样式化组件为其设置样式。但我无法直接访问它。

查看我下载的屏幕。

我需要访问弹出框。 使用 SCSS,我们只需设置 classNames 并将其导入 react 组件即可。但是对于 styled-components,我们有一个特定的范围,它只与 styled 组件部分相关。 我为 CharterPeriodsPopup 创建了样式组件。

【问题讨论】:

【参考方案1】:

来自docs:

将现有的 CSS 框架与 styled-components 集成起来非常简单!您可以在组件旁边使用其现有的类名。

例如,假设您有一个现有应用程序,其中包含两个要再次使用的类:.small.big。如果您希望类始终附加到组件,则应使用the attrs method 附加它。如果您只想在某些情况下附加它,您可以像往常一样使用 className 道具!

// Using .attrs, we attach the .small class to every <Button />
const Button = styled.button.attrs(props => (
  className: "small",
))`
  background: black;
  color: white;
  cursor: pointer;
  margin: 1em;
  padding: 0.25em 1em;
  border: 2px solid black;
  border-radius: 3px;
`;

render(
  <div>
    <Button>Styled Components</Button>
    /* Here we attach the class .big to this specific instance of the Button */
    <Button className="big">The new way to style components!</Button>
  </div>
);

【讨论】:

这与我的问题无关。我只想在样式化组件范围之外访问 className。 糟糕,我误会了。重读后,是否需要在运行时访问该元素?如果是这样,为什么不使用 React ref 来访问原始 DOM 元素(在您想要公开的元素上)? 从那里,如果您需要类名,您可以通过domRef.current.classList 访问它。但是,也许您只需要类名来查询 DOM 元素?如果是这样,那么 React refs 会以惯用的方式完全解决该用例。

以上是关于如何在样式化组件之外设置样式?的主要内容,如果未能解决你的问题,请参考以下文章