从其他文件扩展样式化组件

时间:2019-12-08 03:39:16

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

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

我可以做的一件事是

不是我想做的事的例子:

color

此示例将继承我的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 ) } 样式,然后允许我扩展。这种解决方案的问题是,如果我决定添加更多按钮,则总是必须回到该文件,然后添加不同的变体,这可能会开始使该文件变得非常笨拙和混乱。

理想情况下,我想从App.tsx文件或我正在使用Button的哪个文件中扩展<Button>


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

Button.tsx

<Button>

App.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
  )
}

1 个答案:

答案 0 :(得分:0)

在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;
  `