【问题标题】:Styled component with access to React component state?可以访问 React 组件状态的样式化组件?
【发布时间】:2019-04-12 00:11:10
【问题描述】:

如何让一个样式化的组件根据渲染它的 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:无法读取未定义的属性“dark” 在新容器中

【问题讨论】:

    标签: reactjs styled-components


    【解决方案1】:

    实现这一点的最佳方法是将 prop 传递给您从 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 控制主题!

    这样做有助于提高代码的可读性,并遵循文档的建议。

    【讨论】:

    • 我喜欢这样,但我在呼叫站点收到错误消息。 [ts] 类型“IntrinsicAttributes & IntrinsicClassAttributes, HTMLDivElement>, any>, any, any>> & Readonly<...> & Readonly'。我在同一主题github.com/styled-components/styled-components/issues/630 上发现了这个问题,并提出了许多解决方案。我还没弄清楚哪个是最好的。
    • 嗯,我不使用ts。但我认为如果你用 type ElementProps = { dark: boolean } 之类的道具做 ${(p: ElementProps)=&gt; props.dark ...},这可能会消除错误!
    • 谢谢!这是我添加到您的答案中以使其正常工作的内容: interface OuterWrapperProps { dark: boolean; } const OuterWrapper = styled.div` ... `;
    • 好主意!我已添加到您的答案中。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-09-26
    • 2018-09-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-15
    • 1970-01-01
    相关资源
    最近更新 更多