可以访问 React 组件状态的样式化组件?

Styled component with access to React component state?

如何让样式化的组件根据呈现它的 React 组件的状态呈现不同的 css 规则?

以下不起作用:

class Container extends React.Component<ContainerProps, ContainerState> {
  constructor(props: ContainerProps) {
    super(props);
    this.state = {
      highlight: true,
      dark: false
    };
  }

  OuterWrapper = styled.div`
    display: inline-block;
    padding: 20px;
    ${this.state.dark && `
      background-color: 'gray';
    `};
  `;

    return (
      <this.OuterWrapper>
          ...
      </this.OuterWrapper>
    );

}

TypeError: Cannot read property 'dark' of undefined at new Container

实现这一点的最佳方法是将道具传递给您从 styled-comopnent 获得的元素。

// outside of the component
interface OuterWrapperProps { 
    dark: boolean; 
}

const OuterWrapper =  styled.div<OuterWrapperProps>`
    display: inline-block;
    padding: 20px;
    ${props => props.dark && css`
        background-color: 'gray';
    `};
`; 

当您渲染该元素时:

...
<OuterWrapper dark={this.state.dark}> ... </OuterWrapper>
...

而且您仍然可以通过 state 控制主题!

Doing so, helps the readability of your code, as well as following what the docs suggest.