【问题标题】:TS errors when trying to use props inside styled-component尝试在样式组件中使用道具时出现 TS 错误
【发布时间】:2018-08-28 14:43:26
【问题描述】:

我正在使用带有类型脚本的样式组件,实际上阅读docs。当它是简单的样式时,不使用道具 - 一切顺利:

interface IButtonWithIcon {
  children: string,
  type?: string,
  size?: number,
}

const ButtonWithIcon = styled<IButtonWithIcon, 'button'>('button')`
  color: black;
  border-radius: 5px;
  cursor: pointer;
`;

但是当我尝试时,甚至只是简单地将道具记录到控制台,如下所示:

const ButtonWithIcon = styled<IButtonWithIcon, 'button'>('button')`
  ${console.log}
  color: black;
  border-radius: 5px;
  cursor: pointer;
`;

TS 开始抱怨:

类型参数 '{ (message?: any, ... optionalParams: any[]): void; (message?: any, ... optionalParams: any[]): voi...' 不可分配 到“插值”类型的参数。输入'{(消息?:任何, ...可选参数:任何[]):无效; (消息?:任何,...可选参数: any[]): voi...' 不可分配给类型 'ReadonlyArray | 插值...'。 类型 '{ (message?: any, ... optionalParams: any[]): void; 中缺少属性 'concat' (消息?:任何,...可选参数: 任何[]): voi...'。

如果我添加注释,错误消息会发生变化:

const ButtonWithIcon = styled<IButtonWithIcon, 'button'>('button')`
${(props: IButtonWithIcon): void => console.log(props)}
color: black;
border-radius: 5px;
cursor: pointer;
`;

'(props: IButtonWithIcon) => void' 类型的参数不可赋值 到“插值>”类型的参数。类型 '(props: IButtonWithIcon) => void' 不可赋值 键入'ReadonlyArray |插值...'。 类型“(props: IButtonWithIcon) => void”中缺少属性“concat”。

下面的代码有什么问题?

【问题讨论】:

    标签: typescript styled-components


    【解决方案1】:

    插入到 CSS 中的函数必须返回一些内容。试试:

    const ButtonWithIcon = styled<IButtonWithIcon, 'button'>('button')`
      ${(props) => { console.log(props); return ""; }}
      color: black;
      border-radius: 5px;
      cursor: pointer;
    `;
    

    【讨论】:

      猜你喜欢
      • 2019-07-01
      • 2021-03-17
      • 2019-02-20
      • 2021-11-16
      • 2019-09-20
      • 2013-10-02
      • 2021-01-15
      • 2020-07-27
      • 2021-05-10
      相关资源
      最近更新 更多