2

使用emotionhttps://github.com/emotion-js/emotion)我知道我可以使用以下内容进行主题cssstyled

const carouselCss = ({ theme }) => css`
 .. css properties etc
`;

const CarouselDiv = styled('div')`
  ${carouselCss};
`;

然后在 JSX 中:

<ThemeProvider theme={{ stuff: 'blah' }}>
  <CarouselDiv>
        ..
  </CarouselDiv>
</ThemeProvider>

但是有没有什么优雅的方式来主题化css- 不喜欢使用组件styles化,因为我想保留 JSX 中的语义 html 元素(也有大量的代码库,并且更容易从 sass 迁移到情感而无需使用styled

我知道我可以做类似的事情:

const carouselCss = (theme) => css`
 .. css properties etc
`;

然后jsx:

<div className={carouselCss(this.props.theme)}>
..
</div>

但这意味着一直从组件传递一个主题道具——这有点麻烦

有一个更好的方法吗 ?以某种方式包装css一些东西,以便注入主题变量?

4

2 回答 2

2

ThemeProvider会给你的。这是一个同时显示styledcss选项的示例:

/** @jsx jsx */
import { jsx } from '@emotion/core'
import styled from '@emotion/styled'
import { ThemeProvider } from 'emotion-theming'

const theme = {
  colors: {
    primary: 'hotpink'
  }
}

const SomeText = styled.div`
  color: ${props => props.theme.colors.primary};
`

render(
  <ThemeProvider theme={theme}>
    <SomeText>some text</SomeText>
    <div css={theme => ({ color: theme.colors.primary })}>
      some other text
    </div>
  </ThemeProvider>
)
于 2019-09-03T13:43:20.137 回答
0

您可以使用主题 HoC。但是如果你关心的是 prop 传递给滑块,这个 HoC 基本上是在做同样的事情,即theme注入this.props.theme. 就个人而言,如果可能的话,我会使用ThemeProvider API,也许使用函数式主题,如文档中所指出的:

// function-style theme; note that if multiple <ThemeProvider> are used,
// the parent theme will be passed as a function argument

const adjustedTheme = ancestorTheme => ({ ...ancestorTheme, color: 'blue' });
于 2018-09-03T12:28:43.593 回答