【问题标题】:ThemeProvide used with Typescript is giving an error与 Typescript 一起使用的 ThemeProvide 出现错误
【发布时间】:2021-05-19 12:36:04
【问题描述】:

我想创建一个组件

const StyledDiv = styled.div`
width: 10rem;
height: 3rem;
border-radius: 0.2rem;
background-color: ${({ theme, colorVariant, colorType }) => theme.colors[colorType]. 
 [colorVariant]}
`;

但显示错误

类型 'Pick, "slot" 上不存在属性 'colorVariant' | “风格” | “标题” | ... 252 更多... | "css"> & { ...; } & ThemeProps<...>'。

这是我设置的主题

export default {
  'colors' : {
    'blue' : {
      '100' : '#232f3e',
      '200' : '#233d51',
      '300' : '#006170',
      '400' : '#008296',
      '450' : '#008091',
      '500' : '#d4e4e6',
      '600' : '#e5f2f3',
    },
    'grey' : {
      '600' : '#8ca1a3',
      '700' : '#768283',
      '800' : '#e7e9e9',
      '900' : '#ffffff',
    },
    'red' : {
      '1000' : '#b40909',
    },
    'green' : {
      '1100' : '#417505',
    },
    'yellow' : {
      '1200' : '#f5a623',
    }
  }
};

【问题讨论】:

    标签: javascript typescript styled-components themeprovider


    【解决方案1】:

    你在使用styled-components吗?如果是这样,似乎 div 方法也需要一个参数作为您需要的扩展道具。这就是我的意思:

    const StyledDiv = styled.div<{ colorVariant: string, colorType: string }>`
      width: 10rem;
      height: 3rem;
      border-radius: 0.2rem;
      background-color: ${({ theme, colorVariant, colorType }) => theme.colors[colorType]. 
       [colorVariant]}
    `;
    

    【讨论】:

      【解决方案2】:

      我发现的一种方法是

      
      interface IStyledColorBar {
        colorVariant: string,
        colorType: string,
      };
      
      type StyledProps<T = {}> = React.DetailedHTMLProps<React.HTMLAttributes<HTMLDivElement> & Partial<T>, HTMLDivElement>;
      
      const StyledDiv = styled.div <StyledProps <IStyledColorBar>>`
        width: 10rem;
        height: 3rem;
        border-radius: 0.2rem;
        background-color: ${({ theme, colorVariant, colorType }) => theme.colors[colorType][colorVariant]}
      `;
      
      

      我从 https://github.com/emotion-js/emotion/issues/802#issuecomment-444181912

      【讨论】:

        猜你喜欢
        • 2016-08-28
        • 1970-01-01
        • 2020-10-26
        • 2021-10-08
        • 2016-10-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多