網站搜尋

reactjs - 使用 styled-components 和 typescript 覆寫 props


我正在使用一個具有必填屬性的組件。我想在設置該屬性後對該組件進行樣式設置,並且在渲染時不必再次設置它。如果我不再次設置,Typescript 會抱怨。

我想做的事情大意是:

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

在渲染時不需要設置 icon。

如果我這樣做

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

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

我在渲染時仍然需要設置 icon。

有什麼方法可以達成這個嗎,還是我唯一的出路就是用 typescript-magic 修改 Arrow 的屬性?

使用

  • typescript 3.7.5
  • react 16.12.0
  • styled-components 5.0.1

答案#1

styled-components 有一個名為 attrs 的 API,讓你可以將屬性附加到 DOM 元素或元件上。

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

`;

文件