【问题标题】:How to use Styled API with typescript and props如何将 Styled API 与 typescript 和 props 一起使用
【发布时间】:2019-06-12 15:17:36
【问题描述】:

我正在尝试为组件设置样式(使用新的样式化 api,不要与 StyleComponents 混淆)。

const FixedWidthCell = styled(TableCell)((props: { width: number }) => ({
  width: props.width || 20,
  textAlign: "center",

})) 

问题是 TS 在使用时抱怨宽度不是组件道具的一部分。我的解决方法是:

const FixedWidthCell = styled(TableCell)((props: { width: number }) => ({
  width: props.width || 20,
  textAlign: "center",
})) as React.ComponentType<TableCellProps & { width?: number }>;

但这让我失去了“css属性”中的打字,这不是什么大事,但我很确定我做错了什么,有没有更好的方法呢?

【问题讨论】:

标签: typescript material-ui


【解决方案1】:

我使用这样的道具:

const MyCard = styled(({backgroundColor, color, ...other}) => <Card {...other}/>)({
  height: '100%',
  backgroundColor: props => props.backgroundColor,
  color: props => props.color,
});

所以对于您的示例,这应该可以:

const FixedWidthCell = styled(({width, ...other}) => <TableCell{...other}/>)({
  width: props => props.width ? props.width : 20,
  textAlign: "center",
})) 

【讨论】:

    猜你喜欢
    • 2018-03-18
    • 2018-04-15
    • 2020-03-02
    • 2022-07-29
    • 1970-01-01
    • 2022-08-18
    • 2016-07-27
    • 2020-02-09
    • 2019-03-26
    相关资源
    最近更新 更多