在样式化组件中共享样式的惯用方式? [英] idiomatic way to share styles in styled-components?
问题描述
试图将一些代码从jss移植到样式化组件,jss代码类似于:
trying to port some code from jss to styled-components, jss code looks something like:
//...
const styles = {
myStyles: {
color: 'green'
}
}
const {classes} = jss.createStyleSheet(styles).attach()
export default function(props) {
return (
<div>
<Widget1 className={classes.myStyles}/>
<Widget2 className={classes.myStyles}/>
</div>
)
}
我的问题是在多个组件之间实现相同样式共享的惯用方式是什么?
my question is what would be the idiomatic way to accomplish this sharing of the same styles across multiple components?
推荐答案
您可以共享实际的CSS字符串,也可以共享 styled-components
组件:
You can either share actual CSS strings or share styled-components
components:
- 共享CSS字符串:
import {css} from 'styled-components'
const sharedStyle = css`
color: green
`
// then later
const ComponentOne = styled.div`
${sharedStyle}
/* some non-shared styles */
`
const ComponentTwo = styled.div`
${sharedStyle}
/* some non-shared styles */
`
- 共享实际的
样式化组件
:
const Shared = styled.div`
color: green;
`
// ... then later
const ComponentOne = styled(Shared)`
/* some non-shared styles */
`
const ComponentTwo = styled(Shared)`
/* some non-shared styles */
`
更新:基于评论中的问题,我创建了一个示例,以显示将道具传递给样式组件的 css
函数的方式与将道具传递给组件本身的方式相同: https://codesandbox.io/s/2488xq91qj?fontsize=14 . styled-components
的官方建议是始终包装要在 css
标记函数中传递给 styled-components
的字符串.在此示例中, Test
组件通过嵌入在通过调用 css
函数创建的 cssString
变量中的传入道具接收背景色和前景色.
Update: Based on questions in the comments, I created an example to show that passing props to styled-components's css
function works the same way as passing props to the components themselves: https://codesandbox.io/s/2488xq91qj?fontsize=14. The official recommendation from styled-components
is to always wrap strings you will pass to styled-components
in the css
tag function. In this example, the Test
component receives it background and foreground colors through passed-in props embedded in the cssString
variable created by invoking the css
function.
这篇关于在样式化组件中共享样式的惯用方式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!