Styled component with access to React component state?

丶灬走出姿态 提交于 2019-12-08 08:22:51

问题


How can I get a styled component to render different css rules depending on the state of the React component in which it is rendered?

The below does not work:

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


回答1:


The best way to achieve that is through passing a prop to the element that you get from 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';
    `};
`; 

And when you render that element:

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

And you still have the control over the theme from your state!

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



来源:https://stackoverflow.com/questions/53208522/styled-component-with-access-to-react-component-state

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!