在样式组件中共享样式的惯用方法?

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组件:

  • 分享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 */
`
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)

  • 您还可以创建一个与另一个组件具有相同 css 规则的新组件,但只需使用 [withComponent](https://www.styled-components.com/docs/api#withcomponent) 即可更改 html 标签。简单示例:`const PrimaryLink = PrimaryButton.withComponent('a');` (2认同)

Sag*_*b.g 7

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)


Gab*_*son 5

除了上面的两个答案之外,您还可以在标签之间共享样式,如下所示:

const MyText = styled.div`
  color: orange;
`

const MyLink = MyText.withComponent("a")
Run Code Online (Sandbox Code Playgroud)