简体   繁体   English

React styled-components:如何设置隐式渲染组件的样式?

[英]React styled-components: How to Style Implicitly Rendered Components?

I am using styled-components to implement a light/dark theme into my application.我正在使用styled-components在我的应用程序中实现浅色/深色主题。 Not sure if it matters too much, but I am using TypeScript.不确定它是否太重要,但我使用的是 TypeScript。 I am still pretty new to React and TS.我对 React 和 TS 还是很陌生。

This is straightforward when the component is a basic HTML element:当组件是基本 HTML 元素时,这很简单:

export const StyledEllipsis = styled.div`
  &:hover {
    box-shadow: 0px 0px 10px 1px ${props => props.theme.shadow};
  }
`

Or on a custom component (I may or may not own the type).或者在自定义组件上(我可能拥有也可能不拥有该类型)。 Here I am styling the ResponsiveGridLayout from react-grid-layout :在这里,我从react-grid-layout设置ResponsiveGridLayout的样式:

export const StyledReactGridLayout = styled(ResponsiveGridLayout)`
  background-color: ${props => props.theme.tertiary};
`

However I get tripped up when I need to styled components that I do not explicitly render.但是,当我需要对未明确渲染的组件进行样式设置时,我会被绊倒。 For the examples above, somewhere in code I obviously have:对于上面的示例,我显然在代码中的某处:

...
  <StyledReactGridLayout> ... </StyledReactGridLayout>
...

But what about styling say the children of <StyledReactGridLayout/> that I don't render myself?但是,我不渲染自己的<StyledReactGridLayout/>的孩子的样式呢? In the DOM I can see other child components that react-grid-layout renders, such as <ReactGridItem/> .在 DOM 中,我可以看到react-grid-layout呈现的其他子组件,例如<ReactGridItem/> What if I want to change the theme on this component?如果我想改变这个组件的主题怎么办?

You can simply get the child components class names via the browser inspector and style them like this:您可以通过浏览器检查器简单地获取子组件 class 名称并将它们设置为:

export const StyledReactGridLayout = styled(ResponsiveGridLayout)`
  background-color: ${props => props.theme.tertiary};

  .react-grid-item {
    background-color: // whatever color u want (u can use props here too);
  }
`

Nesting works in styled-components like sass.嵌套适用于 sass 等样式组件。

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

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