代码之家  ›  专栏  ›  技术社区  ›  Leon Gaban

如何在组件内部使用StyledComponents主题

  •  0
  • Leon Gaban  · 技术社区  · 7 年前

    下面我创建了一个名为Link的样式。然而,这个主题是内在的 this.props Link

    import React from 'react';
    import styled from 'styled-components';
    import { withTheme } from 'styled-components';
    
    export const Link = styled.p`
      position: absolute;
      z-index: 10;
      bottom: 20px;
      right: 300px;
      width: 100%;
      font-size: 1.5rem;
      text-align: right;
      cursor: pointer;
    
      a {
        color: ${theme.apricot};  // <-- error
        cursor: pointer;
    
        :hover {
          color: ${theme.offWhite};   // <-- error
        }
      }
    `;
    
    class NomicsLink extends React.Component {
      render() {
        console.log(this.props.theme);
        return (<Link>Powered by <a href="https://nomics.com/" target="blank">Nomics APIs.</a></Link>)
      }
    }
    
    export default withTheme(NomicsLink);
    

    此console.log打印以下内容:

    { red: '#FF0000',
      black: '#393939',
      grey: '#3A3A3A',
      lightgrey: '#E1E1E1',
      offWhite: '#EDEDED',
      apricot: '#FEBE7E',
      margin: 0,
      padding: 0 }
    
    1 回复  |  直到 7 年前
        1
  •  1
  •   Agney Sidharth yadav    7 年前

    全部的 styled-components theme 自动支撑。

    您可以通过以下方式在样式化组件中访问它们:

    const Link = styled.a`
      color: ${props=>props.theme.apricot};
    `;
    

    有关主题化的更多选项,请参见 docs