如何设置嵌套有“styled-components”的组件的样式?

How do I style a component that has `styled-components` nested in it?

我是 styled-components 的新手。我正在尝试为 MyComponent 设置样式以应用于 styled-component.

export const Relative = styled.div`
  position: relative;
`

export const Container = ({ children }) => {
  return <Relative>
    <AnotherComponent/>
    {children}
  </Relative>
}

export const MyComponent = () => <Container>/* */</Container>

如何在不编辑 MyComponent 的情况下使用 styled-componentsMyComponent 中设置 Container 的样式?

您需要将 Container 包装到另一个容器中,例如:

const MyComponentContainer = styled(Container)`
  ...custom styles
`

这也可以帮助:Styling any component

当您使用 styled(YourComponent) 时,假设 YourComponent 是普通组件而不是 styled-component,这将自动为组件提供 className 属性 .你只需要把它放在某个地方。

export const Relative = styled.div`
  position: relative;
`

export const Container = ({ children }) => {
  return (
    <Relative>
      <AnotherComponent/>
      {children}
    </Relative>
  )
}

export const MyComponent = ({ className, children }) => {
  return (
    <div className={className}>
      <Container>
        {children}
      </Container>
    </div>
  )
}

export const CustomMyComponent = styled(MyComponent)`
  // Styles inside here will be applied to the root element of MyComponent
`;