首页 > 解决方案 > 样式化组件 w/o defaultProps w/ typescript

问题描述

我正在将 React 样式组件库更新为:

  1. 应用 TypeScript (v4.1)
  2. 消除 defaultProps 的使用(因为它显然在 React 折旧列表中)

我正在就关于 Typescript 的新模式寻求一般建议,我知道可能有更好的方法来处理默认道具。只是寻找对不同替代方案的有意义的讨论。谢谢!

// theme comes from styled-componets theme prover and is typed

// Typing

type Clr = 'red' | 'blue' | 'green'
type Int = 'L' | 'D'

type TBox = {
  clr: Clr,
  int: Int,
}

interface IBox {
  clr: Clr,
  int: Int,
  children: JsxElement[]
}

// OLD Pattern - using defaultProps

export const Box = styled.div<IBox>`
  background-color : ${({theme, clr, int})=>theme.fnt.clr[clr][int]};
  height: 50px;
  width: 100px;
`

Box.defaultProps = {
  clr: 'green',
  int: 'D'
}

// NEW Pattern - without defaultProps - using a wrapper 

export const Box2A: (props: Readonly<Partial<IBox>>) => JSX.Element = (props) => {
  return <Box2Style {...Box2DefaultProps} {...props} />;
};

const Box2Style = styled.div<TBox>`
  background-color : ${({theme, clr, int})=>theme.fnt.clr[clr][int]};
  height: 50px;
  width: 100px;
`
const Box2DefaultProps: TBox = {
  clr: 'green',
  int: 'D'
}

标签: reactjstypescriptstyled-components

解决方案


附加额外的道具

为了避免不必要的包装器将一些道具传递给渲染的组件或元素,您可以使用.attrs构造函数。它允许您将其他道具(或“属性”)附加到组件。

export const Box = styled.div<TBox>` // can use IBox interface or TBox type
  background-color : ${({ theme, clr, int }) => theme.fnt.clr[clr][int]};
  height: 50px;
  width: 100px;
`

Box.defaultProps = {
  clr: 'green',
  int: 'D'
}

成为

export const Box = styled.div.attrs<TBox>(({ clr, int }) => ({
  clr: clr || 'green',
  int: int || 'D',
}))<TBox>` // can use IBox interface or TBox type
  background-color : ${({ theme, clr, int }) => theme.fnt.clr[clr][int]};
  height: 50px;
  width: 100px;
`

或者

export const Box = styled.div.attrs<TBox>(({ clr = "green", int = "D" }) => ({
  clr,
  int,
}))<TBox>` // can use IBox interface or TBox type
  background-color : ${({ theme, clr, int }) => theme.fnt.clr[clr][int]};
  height: 50px;
  width: 100px;
`

无论如何,我都不是打字稿专家,因此可能需要调整界面,并且我发现了一个关于打字稿和语法的封闭 github问题。.attrs


推荐阅读