【问题标题】:Extend a Styled Component from a different file从不同的文件扩展样式化组件
【发布时间】:2020-04-01 13:46:26
【问题描述】:

我想要实现的是在不同文件中使用此组件时能够为我的 Button.tsx 添加额外的样式(本质上是扩展样式)。正如您在我的Button.tsx 中看到的那样,我已经定义了一些我希望按钮具有的默认样式,但是当我在我的应用程序中使用更多按钮时,我可能想要更改backgroundcolor 等。

我能做的一件事是:

我不想做的例子:

import React from 'react'
import styled from 'styled-components'

interface IButton = {
  children: string
}

export default function Button({ children }: IButton) {
  const Button = styled.button`
    padding: 1em;
    background: #ccc;
    border-radius: 5px;
  `
  const RedButton = styled(Button)`
    // Inherits all of the styles from Button.
    background: red;
  `

  return (
    <Button>{children}</Button
  )
}

这个例子将继承我的Button 样式,然后允许我扩展。这个解决方案的问题是,如果我决定添加更多按钮,我将总是不得不回到这个文件,然后添加不同的变体,这可能会开始使这个文件变得非常笨重和混乱。

理想情况下,我想从 App.tsx 文件中扩展我的 &lt;Button&gt;,或者我正在使用我的 &lt;Button&gt; 的哪个文件。


如何调整下面的代码来实现这一点?

Button.tsx

import React from 'react'
import styled from 'styled-components'

interface IButton = {
  children: string
}

export default function Button({ children }: IButton) {
  const Button = styled.button`
    padding: 1em;
    background: #ccc;
    border-radius: 5px;
  `

  return (
    <Button>{children}</Button
  )
}

App.tsx

import React from 'react'
import styled from 'styled-components'

export default function App() {
  return (
    {/* This button would render with the default styles from Button.tsx */}
    <Button>Button One</Button>
    {/* This button would render with extended styles, a blue background for example */}
    <Button>Button Two</Button>
  )
}

【问题讨论】:

    标签: reactjs typescript styled-components css-in-js


    【解决方案1】:

    在您的 App.tsx 中您也可以这样做:

      const BlueButton = styled(Button)`
        background: blue;
      `
    

    styled-components 的作用是创建一个背景为蓝色的类并将其传递给您的 Button。所以在你的 Button.tsx 中你需要接受 css 类

    export default function Button({ className, children }: IButton) {
      const Button = styled.button`
        padding: 1em;
        background: #ccc;
        border-radius: 5px;
      `
    
      return (
        <Button className={className}>{children}</Button
      )
    }
    

    编辑 另一种方法是像这样导出样式

    const BaseStyles = css`
        padding: 1em;
        background: #ccc;
        border-radius: 5px;
    `
    
    const BaseButton = styled.button`
        ${BaseStyles}
    `
    

    然后覆盖样式

     const BlueButton = styled.button`
        ${BaseStyles}
        background: blue;
      `
    

    【讨论】:

    • 另外,似乎特异性并没有优先考虑 &lt;BlueButton&gt; 样式,它只有在我添加重要时才会起作用:background: blue !important;
    • 你可以像这样添加样式:&& { background: blue; }。这将为覆盖的样式提供更高的优先级
    • 我居然才找到这个方法,难道只有这个方法吗?看起来有点像黑客
    • 恐怕是这样,这就是css类现在的工作方式,此时与样式组件无关。
    • &amp;&amp; 只是复制类名以赋予它更高的特异性,如果&lt;BlueButton&gt; 在编译时出现在&lt;Button&gt; 之后,它不会有更高的特异性吗?
    猜你喜欢
    • 2020-06-12
    • 2020-05-02
    • 1970-01-01
    • 2019-03-28
    • 2020-01-09
    • 1970-01-01
    • 2019-06-04
    • 2019-12-16
    • 2020-08-20
    相关资源
    最近更新 更多