【发布时间】:2020-04-01 13:46:26
【问题描述】:
我想要实现的是在不同文件中使用此组件时能够为我的 Button.tsx 添加额外的样式(本质上是扩展样式)。正如您在我的Button.tsx 中看到的那样,我已经定义了一些我希望按钮具有的默认样式,但是当我在我的应用程序中使用更多按钮时,我可能想要更改background 或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
)
}
这个例子将继承我的Button 样式,然后允许我扩展。这个解决方案的问题是,如果我决定添加更多按钮,我将总是不得不回到这个文件,然后添加不同的变体,这可能会开始使这个文件变得非常笨重和混乱。
理想情况下,我想从 App.tsx 文件中扩展我的 <Button>,或者我正在使用我的 <Button> 的哪个文件。
如何调整下面的代码来实现这一点?
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