样式化组件中的样式化嵌套组件 [英] Styling Nested Components in Styled-Components

查看:38
本文介绍了样式化组件中的样式化嵌套组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用样式化组件在 React 中创建了一个下拉组件.以下是该组件的简化轮廓:

I have created a Dropdown Component in React using Styled Components. Here is a simplified outline of the component:

const Dropdown = (
    <DropdownBase>
      <Trigger>
        {title}
      </Trigger>
      <Submenu>
        {children}
      </Submenu>
    </DropdownBase>
  )

const DropdownBase = styled.div`
  /* Default Styles */
`

const Trigger = styled(Link)`
  /* Default Styles */
`

const Submenu = styled.div`
  /* Default Styles */
`

现在,当我导入和使用组件时,我希望能够覆盖嵌套组件的默认样式(即,DropdownBaseTrigger子菜单).我希望能够使用样式化组件覆盖这些默认样式.问题是,我没有导入那些嵌套组件——我只导入了 Dropdown 组件——就像这样:

Now, when I import and use the component I want to be able to override the default styles of the nested components (i.e., DropdownBase, Trigger and Submenu). And I want to be able to override those default styles using Styled Components. The problem is, that I do not import those nested components -- I only import the Dropdown component -- like this:

import { Dropdown } from '../path/to/dropdown'

<Dropdown />

所以我想知道,当我使用样式化组件导入父组件时,如何覆盖那些嵌套组件?

So I am wondering, how can I override those nested components when I import the parent component using Styled Components?

谢谢.

推荐答案

最好的方法是从 Dropdown 组件中导出 DropdownBase、Trigger 和 Submenu,然后将它们与 Dropdown 一起导入并像这样覆盖:

The best way to do this would be to export DropdownBase, Trigger, and Submenu from your Dropdown component, then import them along with Dropdown and override this like this:

import { Dropdown, DropdownBase, Trigger, Submenu } from '../path/to/dropdown'
import styled from 'styled-components'

const MyComponent = () => {
  return <StyledDropdown />
}

const StyledDropdown = styled(Dropdown)`
  ${DropdownBase} {
    // custom styles
  }

  ${Trigger} {
    // custom styles
  }

  ${Submenu} {
    // custom styles
  }
`

这很有效,因为它针对特定的子样式组件.

This works well because it targets the specific child styled components.

或者,您可以根据他们的标签或子订单来定位他们,但如果您更新 Dropdown 组件,这可能会失败.

Alternatively, you could target them based on their tag or child order, but this may fail if you make updates to the Dropdown component.

这篇关于样式化组件中的样式化嵌套组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆