【问题标题】:Override props with styled-components and typescript使用样式组件和打字稿覆盖道具
【发布时间】:2020-06-03 09:50:28
【问题描述】:

我正在使用具有所需属性的组件。 我想使用所述属性集来设置该组件的样式,并且在渲染时不需要再次设置它。如果我不重新设置,Typescript 会报错。

我想做的事情的要点:

const Arrow = styled(<Icon icon={"ArrowRight"}/>)`
    ...
`;

渲染时不需要设置icon。

如果我这样做

const Arrow = styled(Icon)`
    ...
`;

Arrow.defaultProps = {
    icon: "ArrowRight",
};

渲染时我还是要设置icon。

有什么方法可以实现这一点,或者是我用 typescript-magic 修改 Arrow 道具的唯一方法吗?


使用

  • 打字稿 3.7.5
  • 反应 16.12.0
  • 样式化组件 5.0.1

【问题讨论】:

    标签: reactjs typescript styled-components


    【解决方案1】:

    styled-components 有一个名为 attrs 的 API,因此您可以将属性附加到 DOM 元素或组件。

    const Arrow = styled(Icon).attrs(props => ({
      icon: props.icon // or whatever you want here
    }))`
    
    `;
    

    Docs

    【讨论】:

    • 谢谢?我虽然 attrs 也不能解决打字稿部分
    猜你喜欢
    • 2021-08-24
    • 2020-02-17
    • 2021-07-11
    • 2020-11-02
    • 2021-03-04
    • 2021-06-07
    • 2020-06-27
    • 2021-05-02
    • 2019-01-02
    相关资源
    最近更新 更多