如何将Styled-Component主题变量传递给组件?

时间:2018-04-14 18:14:52

标签: reactjs styled-components

在我的React + StyledComponent应用程序中,我有一个像这样的主题文件:

theme.js:

const colors = {
  blacks: [
    '#14161B',
    '#2E2E34',
    '#3E3E43',
  ],
};

const theme = {
  colors,
};

export default theme;

目前,我可以轻松地使用这些颜色来设置我的组件样式:

const MyStyledContainer = styled.div`
  background-color: ${(props) => props.theme.colors.blacks[1]};
`;

问题是,如何将黑色[1]传递给Component作为颜色的支柱,如下所示:

<Text color="black[1]">Hello</Text>

Text.js是:

const StyledSpan = styled.span`
  color: ${(props) => props.theme.colors[props.color]};
`;

const Text = ({
  color,
}) => {
  return (
    <StyledSpan
      color={color}
    >
      {text}
    </StyledSpan>
  );
};

Text.propTypes = {
  color: PropTypes.string,
};

export default Text;

目前上述内容无声地失败并在DOM中重新发送以下内容:

<span class="sc-brqgn" color="blacks[1]">Hello</span>

关于如何让它发挥作用的任何想法?谢谢

4 个答案:

答案 0 :(得分:3)

编辑:更新为使用样式组件withTheme HOC

新答案

您可以将组件呈现<Text>包装在样式组件提供的高阶组件(HOC)withTheme中。这使您可以直接在React组件中使用<ThemeProvider>给出的主题。

示例(基于the styled-components docs):

import React from 'react'
import { withTheme } from 'styled-components'
import Text from './Text.js'

class MyComponent extends React.Component {
  render() {
    <Text color={this.props.theme.colors.blacks[1]} />;
  }
}

export default withTheme(MyComponent)

然后你可以做

const MyStyledContainer = styled.div`
    background-color: ${(props) => props.color};
`;

旧答案

您可以导出渲染的主题并传递<Text color={theme.blacks[1]} />

import theme from './theme.js'
...
<Text color={theme.colors.blacks[1]} />

然后你可以做

const MyStyledContainer = styled.div`
    background-color: ${(props) => props.color};
`;

答案 1 :(得分:1)

您可以使用defaultProps

import PropTypes from 'prop-types'

MyStyledContainer.defaultProps = { theme }

答案 2 :(得分:1)

App.js

App获取主题并将颜色传递给Text

import React, { Component } from 'react'
import styled from 'styled-components'

const Text = styled.div`
  color: ${props => props.color || 'inherit'}
`

class App extends Component {
  render() {
    const { theme } = this.props
    return (
      <Text color={theme.colors.black[1]} />
    )
  }
}

export default App

Root.js

Root组件将主题传递给整个应用程序。

import React, { Component } from 'react'
import { ThemeProvider } from 'styled-components'
import theme from './theme'
import App from './App'

class Root extends Component {
  render() {
    return (
      <ThemeProvider theme={theme}>
        <App />
      </ThemeProvider>
    )
  }
}

export default Root

答案 3 :(得分:0)

如果您在 React 和 package main import ( "os" "os/exec" ) func main() { c := exec.Command( "ffmpeg", "-i", "file.webm", "-vf", "select='eq(pict_type, I)'", "-vsync", "vfr", "%d.jpg", ) c.Stderr = os.Stderr c.Run() } 及更高样式的组件中使用函数式组件,则需要利用 v4.x 和样式组件的 useContext。总之,这些允许您不是样式组件的组件内使用您的主题设置。

ThemeContext

进一步阅读样式组件文档:https://styled-components.com/docs/advanced#via-usecontext-react-hook

相关问题