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

How to use StyledComponents theme inside of Component

下面我创建了一个名为 Link 的样式。但是主题在 this.props 内。从道具中获取主题并传递到 Link 样式组件的方法是什么?

ReferenceError: theme is not defined

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 }

所有styled-components自动获得theme道具。

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

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

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