![](/img/trans.png)
[英]use styled-components to share styles between components/elements
[英]idiomatic way to share styles in styled-components?
試圖將一些代碼從 jss 移植到 styled-components,jss 代碼看起來像:
//...
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>
)
}
我的問題是實現跨多個組件共享相同樣式的慣用方式是什么?
您可以共享實際的 CSS 字符串或共享styled-components
組件:
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 */
`
styled-components
:const Shared = styled.div`
color: green;
`
// ... then later
const ComponentOne = styled(Shared)`
/* some non-shared styles */
`
const ComponentTwo = styled(Shared)`
/* some non-shared styles */
`
更新:基於評論中的問題,我創建了一個示例來說明將道具傳遞給 styled-components 的css
函數的工作方式與將道具傳遞給組件本身的方式相同: https ://codesandbox.io/s/2488xq91qj?fontsize= 14 . styled-components
的官方建議是始終在css
標記函數中包裝您將傳遞給styled-components
的字符串。 在此示例中, Test
組件通過調用css
函數創建的cssString
變量中嵌入的傳入道具接收它的背景色和前景色。
除了發布的答案之外,您還可以創建一個接受props
/ theme
並返回css``
的函數。
styled-components
將檢查提供的值的類型,例如: ${shared}
,如果它是一個function
,它將使用相關的props
/ theme
調用它。
import styled, {css} from 'styled-components';
const shared = ({theme, myProp}) => css`
color: ${theme.color};
`
/* ------------ */
const Component1 = styled.div`
${shared};
/* more styles ... */
`
const Component2 = styled.div`
${shared};
/* more styles ... */
`
除了上面的 2 個答案,您還可以在標簽之間共享樣式,如下所示:
const MyText = styled.div`
color: orange;
`
const MyLink = MyText.withComponent("a")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.