ton*_*y_k 24 javascript styled-components jss
试图将一些代码从jss移植到样式组件,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>
)
}
Run Code Online (Sandbox Code Playgroud)
我的问题是在多个组件中实现相同样式共享的惯用方法是什么?
Huy*_*yen 55
您可以共享实际的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 */
`
Run Code Online (Sandbox Code Playgroud)
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 */
`
Run Code Online (Sandbox Code Playgroud)
In addition to the posted answer, you can also create a function that accepts props / theme and returns the css``.
styled-components will check the type of the value provided eg: ${shared} and if its a function it will invoke it with the relevant 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 ... */
`
Run Code Online (Sandbox Code Playgroud)
除了上面的两个答案之外,您还可以在标签之间共享样式,如下所示:
const MyText = styled.div`
color: orange;
`
const MyLink = MyText.withComponent("a")
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7334 次 |
| 最近记录: |